How to automatically add variables to a matrix with each iteration?
이전 댓글 표시
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
채택된 답변
추가 답변 (1개)
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.
카테고리
도움말 센터 및 File Exchange에서 Language Fundamentals에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!