How do I store values from nested loops?
古いコメントを表示
Hi, I'm trying to take the answers of each calculation of "result1" and store them in a vector and I'm not sure how to do it properly. I can only get the resulting matrix to have the ending value repeated over and over. How do I go about this? Thank you.
Here is my current code:
criteria=1E-7;
not_converged=true;
X=[-.99:0.01:0.99];
result1=zeros(size(X));
for x=-.99:.01:0.99
for n=0:20
thetaOld=((((-1).^n).*x.^(2*n+1))/(2*n+1));
while(not_converged)
n=n+1;
thetaNew = thetaOld+((((-1).^n).*x.^(2*n+1))/(2*n+1));
y=abs(thetaNew-thetaOld);
if(y<=criteria)
not_converged=false;
end
thetaOld=thetaNew;
result=[((pi/2)-thetaNew)];
end
end
result1(1,:)=result;
end
result1
1 件のコメント
KSSV
2018 年 2 月 19 日
You need to rethink on your code.....you are running a for loop with index n and you are incrementing it inside while loop.
回答 (1 件)
Star Strider
2018 年 2 月 19 日
Since ‘result’ appears to be a scalar, I would do this:
x = -.99:.01:0.99;
result1 = zeros(size(x));
for k = 1:numel(x)
. . . CODE . . .
result1(k)=result;
end
If ‘result’ is a vector, address it accordingly.
3 件のコメント
Justin Anderson
2018 年 2 月 19 日
Either by
result1(:, k) = result;
if it is a column vector and all results have the same size. Or if they have different sizes use a cell array as result:
result1 = cell(size(x));
...
result1{k} = result;
By the way: The square brackets are a waste of time here:
X = [-.99:0.01:0.99];
result = [((pi/2)-thetaNew)];
Remember that [] is the Matlab operator for array concatenation, but you do not concatenate anything here.
X = -.99:0.01:0.99;
result = ((pi/2)-thetaNew);
Star Strider
2018 年 2 月 19 日
@Jan — Thank you!
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!