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

3 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

John D'Errico
John D'Errico il 26 Gen 2020
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 Commenti
Guillaume
Guillaume il 27 Gen 2020
Modificato: Guillaume il 27 Gen 2020
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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Operating on Diagonal Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by