Diagonal matrix, wishing to solve Ax=b
14 views (last 30 days)
Show older comments
I am not getting any errors, but I am certainly doing something wrong.
I wish to get output that is the result of x for x=b/A
where A is an nxn matrix
b a vector
I am trying to create function called solveDiag(A,b)
instead of getting desired output i get the original matrix A
so my output is:
"ans =
2
the answer is
ans= [3 0 0
0 2 0
0 0 7]"
This what I have:
function [A,b]=solveDiag(A,b)
%A=nxn diagonal matrix
%b=column vector
%n is number of unknowns in matrix
A=[3 0 0 ; 0 2 0 ; 0 0 7];
b=[4 8 21]
for i = 1, 2,...,n do
x(1,:)=b(i)/A(i,i);
fprintf('the answer is',x(1,:))
end
end
11 Comments
Walter Roberson
on 27 Jan 2020
The syntax
for i = 1, 2,...,n do
x(1,:)=b(i)/A(i,i);
is the same as
for i = 1
display(2), ...,n do
x(1,:)=b(i)/A(i,i);
where ...,n do is a line continuation indicator. After the line continuation indicator, everything else on the line would be ignored as a comment. Putting the lines together removing the line continuation indicator, your code is equivalent to
for i = 1
display(2), x(1,:)=b(i)/A(i,i);
And that is why you are getting the ans = 2 .
Remember, in MATLAB, comma outside of a parameter list or [] indicates a statement separator and that the output of the statement just before it is to be displayed.
for i = 1, 2, 3, 4, 5
is
for i = 1
display(2)
display(3)
display(4)
display(5)
and would be completely different than
for i = [1, 2, 3, 4, 5]
because the commas inside the [] list building operation do not indicate statement separator.
for i = 1:5
would be almost the same as for i = [1, 2, 3, 4, 5] but the version with the : operator has some optimization compared to the version with the [] list.
Answers (1)
Les Beckham
on 26 Jan 2020
I thought that I had commented on this question earlier with something that should work for you. Here is the code that I think should work for you.
A = diag([3 2 7])
b = [4 8 21];
b/A
3 Comments
Rik
on 27 Jan 2020
You haven't deleted the question, you have simply edited it to remove any usefulness to any future reader. Don't do that. There is a reason that you can only delete your own question if it hasn't received any answers yet. A stranger on the internet spent time reading, understanding, and answering your question. Removing it is a poor showing of gratitude.
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!