How to store values from a loop?

61 vues (au cours des 30 derniers jours)
John Doe
John Doe le 21 Jan 2014
Commenté : Hanna le 25 Jan 2023
I have a .m function file of Y(x,y), and the fzero command below to find the zero for varying values of y:
if true
for y= 2:0.1:10
x = fzero(@(m) Y(m,y),4);
end
end
however after each loop, the previous value is overwritten, is there a way I can save them all?
Kind Regards,
John.

Réponse acceptée

Bruno Pop-Stefanov
Bruno Pop-Stefanov le 21 Jan 2014
Store them in a vector using an index like in the following:
y = 2:0.1:10;
% For all elements in vector y
for i=1:numel(y)
% Set ith element of vector x
x(i) = fzero(@(m) Y(m,y(i)),4);
end

Plus de réponses (2)

Azzi Abdelmalek
Azzi Abdelmalek le 21 Jan 2014
Modifié(e) : Azzi Abdelmalek le 21 Jan 2014
ii= 2:0.1:10
sol=cell(numel(ii),1)
for y=ii
x = fzero(@(m) Y(m,y),4);
sol{y}=x;
end
celldisp(sol)
  1 commentaire
Alvina Khairun Nisa
Alvina Khairun Nisa le 23 Mai 2017
how to save celldisp(sol) to file.mat?

Connectez-vous pour commenter.


Mahdi
Mahdi le 21 Jan 2014
There are two ways to do this, the following is the less efficient way
x=[];
if true
for y=2:0.1:10
x=[x; fzero(@(m) Y(m,y),4)];
end
end
Basically, the above code will store all the values in each loop in a matrix x. You can also preallocate and create a matrix by using x(i)=rest of it
i=1
for loop
x(i)=
i=i+1;
end
  2 commentaires
John Doe
John Doe le 21 Jan 2014
Thank you
Hanna
Hanna le 25 Jan 2023
Tahnk you Mahdi!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by