Diagonal matrix, wishing to solve Ax=b
조회 수: 16 (최근 30일)
이전 댓글 표시
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
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.
답변 (1개)
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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!