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

조회 수: 3 (최근 30일)
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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 9월 25일
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

추가 답변 (1개)

Image Analyst
Image Analyst 2012년 9월 25일
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.

카테고리

Help CenterFile Exchange에서 Parallel Computing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by