The immediate problem is that the MAGS variable is sliced into using two
different expressions based on ii. From the online doc
# Fixed Index Listing - Within the first-level parenthesis or braces, the
list of indices is the same for all occurrences of a given variable.
There is one way around this language restriction.
for ii = 1:rows
mags1=mags; % note matlab does not actually make a full copy here
parfor k = 1:ksize
mags(:,k,ii) = expm(A*step)*(mags1(:,k,ii-1)+Ainvb)-Ainvb;
However, allow me to make a suggestion along a different line. The above
code pieces together the 3D MAGS matrix one sheet at a time. This requires
moving the newly constructed sheet from the workers at the end of the PARFOR
loop and then BACK to the workers when the PARFOR is re-entered to start
working on the next sheet. I beleive you can reorder the PARFOR/FOR loops
so that MAGS is constructed by columns. The code snippet below approximates
your original code, but the PARFOR loop is only entered once, hence reducing
the amount of data transmitted between the workers and the client.
% the dimensions of a single sheet
NROWS = 40;
NCOLS = 40;
% put the parfor on the outside
% imagine each parfor loop iterate is stacking column vectors
% on top of one another
parfor( idx = 1 : NCOLS )
numSheets = 200; % how tall is the MAGS 3D matrix
% initialize the column being worked on at the "bottom"
col = zeros(NROWS, 1, numSheets);
% now loop from the "bottom" to the "top"
for sheet = 2 : numSheets
% now each column is calculated as the column below it modified in
col( :, 1, sheet ) = col( :, 1, sheet-1) + ones( NROWS, 1 );
% slice the output, put the columns next each other
mags( :, idx, : ) = col;