getting error while trying to write a code to solve general case diagonal Ax=b matrix

I am trying to write code for solve Ax=b
function [x]=solveDiag(A,b,n)
%A = nxn diagonal matrix
%b=1x3 column vector
%n=number of unknowns in diagonal
for i=1,2,...,n do
x(i)=b(i)/A(i,i);
fprintf('%d',x(i,:))
end
end

 採用された回答

John D'Errico
John D'Errico 2020 年 1 月 26 日
You should probably read the getting started tutorials, since you are using syntax that does not do what you think it does in MATLAB. For example, this is NOT how you define a for loop:
for i=1,2,...,n do
Sorry, but not so. As I said, reading the manual is important, since different languages use sometimrs subtly different forms.
In MATLAB, write it like this:
for i=1:n
Next, what does your function return as outputs? A and b. Should you be surprised that it returns A as it was defined?
Worse, you are calling the function with arguments A and b, at least in theory, but then you just define A and b inside the function. I think you think that A and b need to be dclared somehow. They don't.

3 件のコメント

CS
CS 2020 年 1 月 26 日
I originally did have i=1:n, but it kept giving me an error I guess when I saw that for 1,2,... worked i just stuck with it /: i apoligize. It returns b=... and ans= (then what I gave it for A)
okay so give me a second, you've given me much valuable information to work with... i thought to myself "hey, i can give you A & b because they are known, im solving for x right?" THANK YOU VERY MUCH
Guillaume
Guillaume 2020 年 1 月 27 日
編集済み: Guillaume 2020 年 1 月 27 日
Yes,
for i=1,2,...n
dosomething
end
works, if by works you mean it doesn't error. It certainly doesn't do what is expected. In matlab the comma is a separator for statements, pretty much equivalent to a new line and the ... is a comment indicator with the rest of the code on the next line, so the above is equivalent to:
for i = 1 %doesn't really work as a loop, since it only goes through 1
2 %print 2 at the command line
%...n %just a comment
dosomething
end
CS
CS 2020 年 1 月 27 日
I want to thank you all very much

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeOperating on Diagonal Matrices についてさらに検索

質問済み:

CS
2020 年 1 月 26 日

コメント済み:

CS
2020 年 1 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by