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
0 件のコメント
採用された回答
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
0 件のコメント
その他の回答 (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.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!