Diagonal matrix, wishing to solve Ax=b

14 ビュー (過去 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 Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by