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 Comment

You need to rethink on your code.....you are running a for loop with index n and you are incrementing it inside while loop.

Sign in to comment.

Answers (1)

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 Comments

It is meant to be a vector, but how would I go about changing the code so that it works with it in vector form?
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);
@Jan — Thank you!

Sign in to comment.

Asked:

on 19 Feb 2018

Commented:

on 19 Feb 2018

Community Treasure Hunt

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

Start Hunting!