How to use eval in parfor
    15 views (last 30 days)
  
       Show older comments
    
Hello, all:
I got a problem in using Parfor. Matlab says eval can not be used for parfor. Would you please help me see how I can change this format so that it can works?
Additionally, would you please tell me if a structure also can not be used in parfor? The following commands works fine if I use for but when I used parfor, I got errors. Thank you very much
 for i=1:5
    parfor ii=1:10
        eval(['A.B',num2str(i),'.C(ii,1) = ii;'])
    end
 end
0 Comments
Answers (2)
  Steven Lord
    
      
 on 22 Feb 2017
        I'd probably create a sliced output variable C inside the parfor loop and assign that variable to a field of your struct outside the parfor statement as shown in "Slicing structure fields" on this documentation page. Dynamic field names may be of use to you in this outer assignment step.
0 Comments
  Stephen23
      
      
 on 22 Feb 2017
        
      Edited: Stephen23
      
      
 on 22 Feb 2017
  
      N = 10;
A(5).C = [];
for m = 1:5
    V = NaN(1,N);
    parfor n = 1:N
        V(n) = m^n;
    end
    A(m).C = V;
end
This allows you to access the data very simply, e.g.:
>> vertcat(A.C)
ans =
  Columns 1 through 7
           1           1           1           1           1           1           1
           2           4           8          16          32          64         128
           3           9          27          81         243         729        2187
           4          16          64         256        1024        4096       16384
           5          25         125         625        3125       15625       78125
  Columns 8 through 10
           1           1           1
         256         512        1024
        6561       19683       59049
       65536      262144     1048576
      390625     1953125     9765625
and will be much easier to work with than nested structures.
0 Comments
See Also
Categories
				Find more on Loops and Conditional Statements in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

