0

I have the following simple MATLAB code:

B = integer; % Doesn't change
n = integer; % Doesn't change
X = vector; % Doesn't change
Y = vector; % Doesn't change
V_final = zeros(m,4);
residuals_final = zeros(m,1);
parfor q = 1:m
[V_low residuals_low] = customfunction(B, n, X, Y); % function contains loop of n iterations
% V_low is a 2x2 matrix, residuals_low is a floating point number
V_final(q,1) = V_low(1,1);
V_final(q,2) = V_low(1,2);
V_final(q,3) = V_low(2,1);
V_final(q,4) = V_low(2,2);
residuals_final(q) = residuals_low;
end

but get the error: The variable V_final in a parfor cannot be classified. Each iteration is independent of each other and I have pre-assigned everything I thought I needed to. Any help appreciated. Have looked at documentation (hard to relate to this situation, besides thought I'd done the right thing) and other answers to similar questions and either ther're not the same or can't see similarity.

user46655
  • 11
  • 7
  • Have you tried defining an auxiliary variable `V_tmp=[V_low(1,1:2); V_low(2,1:2)];`, then `V_final(q,:) = V_tmp`? The interpreter is not always intelligent enough. – Andras Deak -- Слава Україні Dec 19 '15 at 20:37
  • Sorry, I of course meant `V_tmp=[V_low(1,1:2) V_low(2,1:2)];` – Andras Deak -- Слава Україні Dec 19 '15 at 20:44
  • Thanks for responding Andras. Tried this within parfor loop, same error though: V_tmp = [V_low(1,1:2); V_low(2,1:2)]; V_final(q,1) = V_tmp(1,1); V_final(q,2) = V_tmp(1,2); V_final(q,3) = V_tmp(2,1); V_final(q,4) = V_tmp(2,2); – user46655 Dec 19 '15 at 20:56
  • Still same error with V_tmp=[V_low(1,1:2) V_low(2,1:2)]; I'm using R2015b – user46655 Dec 19 '15 at 20:59
  • The important bit was `V_final(q,:) = V_tmp` instead of element-by-element assignment. Have you tried that? Hmm... and how does your `customfunction` not depend on `q`? – Andras Deak -- Слава Україні Dec 19 '15 at 21:24
  • It works! (Doc Brown moment). Thanks so much Andras. q merely is the number of iterations of the parfor loop. I.e. doing the same thing over and over again (but not expecting the same answer!). Now, why does your solution work and mine didn't? – user46655 Dec 19 '15 at 21:41
  • As I said, the interpreter is not always intelligent enough. It will ony allow expressions which it recognizes to be independently evaluated in the loop, and having indices like in your original seems to confuse it. You have to introduce the auxiliary variable to make it explicit to the interpreter that you're accessing complete slices of `V_final`, independent rows in each iteration. In the end the same thing is happening in the code, but this minor restructuring helps the interpreter better understand the flow of your code. – Andras Deak -- Слава Україні Dec 19 '15 at 22:19

0 Answers0