Info

This question is closed. Reopen it to edit or answer.

How can I keep what a function returns between to calls in a loop ?

1 view (last 30 days)
Hi everybody
This will be a bit hard to explain. I call a function, which return some matrices, in a loop. Imagining that the function my_function returns the matrix X,
First iteration: my_function returns X
Second iteration: my_function uses the precedent X to calculate a new X
And so on.
There are a lot of things I can't do (like using X as both a return and an argument) because of a parfor loop...This loop is the reason I have to use a function here, by the way.
I can't post the whole code here, because it's huge, but here's a glimpse:
for boucle=1:100
parfor i=1:N
X=my_function(some stuff);
end
end
In my function, there is an "if":
function [my_X]=my_function(a lot of stuff)
if boucle==1
some calculations where X isn't needed (for the first "boucle")
else
some calculations where X is needed (uses the X obtained with "boucle-1")
end
a calculation of my_X
end
Of course my function doesn't know my X when I try to reuse it, it's not an argument... Using "global" or "persistent" is impossible because of the parfor loop. I tried using a pointer before remembering there is no such thing in MATLAB...
Any other ideas ? Sorry for my Engrish Have a good evening/morning/whatever

Answers (1)

Edric Ellis
Edric Ellis on 23 Feb 2015
PARFOR can only run when the iterations of the loop are independent. In your case, because the 2:N iterations depend on the value produced in the preceding iteration, this is not the case.
The exception to this is that PARFOR understands various reduction operations, so you can write loops like this:
x = 0;
parfor idx = 1:10
x = x + rand();
end

Community Treasure Hunt

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

Start Hunting!