How to save variables generated inside 'for' loop which contains a function, to the workspace?
Afficher commentaires plus anciens
I have a long code, part of which involves calling a function inside a 'for' loop. Please see code below:
zz = linspace(0,0.2,length);
for qq=1:1:length(zz)
% some stuff %
[Z, AT, AW, W] = myfunc(zz(qq));
A = AT(end,:);
end
'myfunc' is written as a separate .m file. The problem is the variable 'A' or any of the variables returned from the function is not available outside this loop. What can I do save these variables so that I can use them in the next steps of my code?
10 commentaires
Kevin Chng
le 2 Sep 2018
Modifié(e) : Kevin Chng
le 2 Sep 2018
Hi,
Do you mind to share your script? So that we have better picture explain to you.
Variable 'A' should be available in the workspace except your for-loop is inside a function.
Bhaswar Dutta Gupta
le 2 Sep 2018
Stephen23
le 2 Sep 2018
"The script is more than 200 lines of code. It will be difficult to share it here."
Actually it is really easy: just click the paperclip button to upload it as a file.
Bhaswar Dutta Gupta
le 2 Sep 2018
Walter Roberson
le 2 Sep 2018
A = AT(end,:);
should be
A(qq,:) = AT(end,:);
Otherwise you are overwriting all of A each time through the qq loop.
Bhaswar Dutta Gupta
le 2 Sep 2018
Modifié(e) : Bhaswar Dutta Gupta
le 2 Sep 2018
Walter Roberson
le 2 Sep 2018
Where is the A result for qq = 1 to be stored separately for the A result for qq = 2 ? If you only want the final A, the one for qq = length(zz) then why bother to run any iteration other than qq = length(zz) ?
Perhaps you would find it easier to understand as
A{qq} = AT(end,:);
Is it possible that you are using parfor? With you not indexing the output variables by qq, parfor would assume that those variables are local variables that do not need to be preserved after the parfor loop.
Bhaswar Dutta Gupta
le 2 Sep 2018
Modifié(e) : Bhaswar Dutta Gupta
le 2 Sep 2018
Walter Roberson
le 2 Sep 2018
Your loop starts at 2. What happens if length(zz) is 1 ?
Be careful with length(), as it will report 0 if any dimension is empty, and will return the largest dimension otherwise, not a particular dimension.
Bhaswar Dutta Gupta
le 2 Sep 2018
Réponses (1)
ahmed nebli
le 2 Sep 2018
0 votes
u can create an array, and use the function vertcat to store the variable A each time
Catégories
En savoir plus sur Loops and Conditional Statements 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!