How to use eval in parfor

23 vues (au cours des 30 derniers jours)
Baozai
Baozai le 22 Fév 2017
Modifié(e) : Stephen23 le 22 Fév 2017
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

Réponses (2)

Steven Lord
Steven Lord le 22 Fév 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.

Stephen23
Stephen23 le 22 Fév 2017
Modifié(e) : Stephen23 le 22 Fév 2017
Instead of creating numbered field names simply use a non-scalar structure:
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.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by