matlab fix slicing to execute parfor
Just beginning with parallel stuff...
I have a code that boils down to filling the columns of a matrix
A (which is preallocated with
NaNs) with an array of variable length:
A = nan(100); for ii=1:100 hmy = randi([1,100]); %lenght of the array A(1:hmy,ii) = rand(hmy,1); %array end
Simply transforming the
for in a
parfor does not even run
parfor ii=1:100 hmy = randi([1,100]); %how many not NaN values to put in A(1:hmy,ii) = rand(hmy,1); end
because the parfor does not like the indexing:
MATLAB runs loops in parfor functions by dividing the loop iterations into groups, and then sending them to MATLAB workers where they run in parallel. For MATLAB to do this in a repeatable, reliable manner, it must be able to classify all the variables used in the loop. The code uses the indicated variable in a way that is incompatible with classification.
I thought that this was due to the indexing on the first dimension and tried a workaround that did not work (same error message as before):
parfor ii=1:100 hmy = randi([1,100]); tmp = [rand(hmy,1); NaN(size(A,1)-hmy,1)]; A(:,ii) = tmp; end
How can I index
A in order to store the array?
You cant partially change the row or column data in A. You have to do either a full row or full column inside parfor. Here is the updated code.
A = nan(100); parfor ii=1:100 hmy = randi([1,100]); %lenght of the array temp = nan(1,100); temp(1:hmy) = rand(hmy,1); %array A(:,ii) = temp; %updating full row of iith column end
First of all, the output variable (A in this case) will be a sliced variable in case of parfor. Which means this variable will be sliced in different part for parallel calculation. The form of indexing in the sliced variable should be same for all incident. Here, you are creating a random number(hmy) and using (1:hmy) as a index which is changing every now and then. That's why your output variable can't be sliced and you have the error.
If you try with a fixed hmy, then it will be alright.