Diagonal matrix, wishing to solve Ax=b

조회 수: 16 (최근 30일)
CS
CS 2020년 1월 26일
댓글: Abel Medina 2021년 3월 6일
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
Walter Roberson
Walter Roberson 2020년 1월 27일
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.
CS
CS 2020년 1월 27일
Thank you all very much, we have managed to create a function that delivers desired output!
Ignore the first line in command, i first used () to declare c instead of [].
Screen Shot 2020-01-27 at 11.04.03 AM.png

댓글을 달려면 로그인하십시오.

답변 (1개)

Les Beckham
Les Beckham 2020년 1월 26일
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
Rik
Rik 2020년 1월 27일
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.
Abel Medina
Abel Medina 2021년 3월 6일
lol

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by