How to automatically add variables to a matrix with each iteration?

3 vues (au cours des 30 derniers jours)
sono
sono le 25 Sep 2012
I have code that solves an equation and checks against a known value until the error is with in tolerance.
I would like to add the "n" and "error" variables for each iteration to a matrix as they are calculated every time the script loops.
I am guessing I need to add a line right before the end that would append a matrix but I cant seem to locate the necessary syntax.
Thank you.
EX:
n error
1 30.12
2 28.43
3 25.83
etc...
MY CODE:
n = 1;
error = 100;
Strue = (pi^2)/6;
Scalc = 1/(n^2);
while error > 0.001
n = n+1;
Scalc = Scalc + (1/(n^2));
error = 100*((abs(Strue-Scalc))/Strue);
end

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 25 Sep 2012
Strue = (pi^2)/6;
Scalc = 0;
n = 1;
error1 = 1;
while error1 > 0.001
Scalc = Scalc + (1/(n^2));
error1 = 100*((abs(Strue-Scalc))/Strue);
errors(n,:) = [n,error1];
n = n+1;
end

Plus de réponses (1)

Image Analyst
Image Analyst le 25 Sep 2012
You are adding to n each iteration. You could add up error also by doing the same thing:
theError = theError + 100*((abs(Strue-Scalc))/Strue);
Don't use error because you'd override the built in error function. Use a different name instead, like theError.
I'm not sure what you mean by "append a matrix" but in general you do it like this
myMatrix = [myMatrix appendedValue]; % Append appendedValue to myMatrix.

Catégories

En savoir plus sur Parallel Computing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by