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 comentario

KSSV
KSSV el 19 de Feb. de 2018
You need to rethink on your code.....you are running a for loop with index n and you are incrementing it inside while loop.

Iniciar sesión para comentar.

Respuestas (1)

Star Strider
Star Strider el 19 de Feb. de 2018
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 comentarios

Justin Anderson
Justin Anderson el 19 de Feb. de 2018
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?
Jan
Jan el 19 de Feb. de 2018
Editada: Jan el 19 de Feb. de 2018
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
Star Strider el 19 de Feb. de 2018
@Jan — Thank you!

Iniciar sesión para comentar.

Categorías

Preguntada:

el 19 de Feb. de 2018

Comentada:

el 19 de Feb. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by