How do I store values from nested loops?
Afficher commentaires plus anciens
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 commentaire
KSSV
le 19 Fév 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.
Réponses (1)
Star Strider
le 19 Fév 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 commentaires
Justin Anderson
le 19 Fév 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
le 19 Fév 2018
@Jan — Thank you!
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!