How to save variables generated inside 'for' loop which contains a function, to the workspace?
Ältere Kommentare anzeigen
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 Kommentare
Kevin Chng
am 2 Sep. 2018
Bearbeitet: Kevin Chng
am 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
am 2 Sep. 2018
Stephen23
am 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
am 2 Sep. 2018
Walter Roberson
am 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
am 2 Sep. 2018
Bearbeitet: Bhaswar Dutta Gupta
am 2 Sep. 2018
Walter Roberson
am 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
am 2 Sep. 2018
Bearbeitet: Bhaswar Dutta Gupta
am 2 Sep. 2018
Walter Roberson
am 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
am 2 Sep. 2018
Antworten (1)
ahmed nebli
am 2 Sep. 2018
0 Stimmen
u can create an array, and use the function vertcat to store the variable A each time
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!