Parfor Indexing -- Basic question

2 ビュー (過去 30 日間)
Matlab2010
Matlab2010 2013 年 10 月 25 日
回答済み: Matt J 2013 年 10 月 25 日
How do you index into a variable if you dont know the size of the loop?
In the first example below parfor works fine.
A = 1:10;
parfor i = 1:length(A)
tmp = rand(A(i));
B(i) = tmp(1);
end
In this example, parfor doesnt work."cannot be run due to the way variable B is used". Such a situation might occur if the case was more complex where B was only assigned an output under certain conditions (IE you dont know the final size of B at the start).
A = 1:10;
B = [];
parfor i = 1:length(A)
tmp = rand(A(i));
B(end+1) = tmp(1);
end
also doesnt work:
A = 1:10;
B = [];
cnt = 1;
parfor i = 1:length(A)
tmp = rand(A(i));
B(cnt) = tmp(1);
cnt = cnt + 1;
end
Hence my question is, how do you index into B in such a case?

回答 (3 件)

Edric Ellis
Edric Ellis 2013 年 10 月 25 日
Here are two ways you could address this. Firstly, using concatenation:
B1 = [];
parfor idx = 1:1000
x = rand();
if x > 0.5
B1 = [B1, x];
end
end
Or, build B with invalid values and strip them later
B2 = NaN(1, 1000);
parfor idx = 1:1000
x = rand();
if x > 0.5
B2(idx) = x;
end
end
B2 = B2(~isnan(B2));
  1 件のコメント
Matt J
Matt J 2013 年 10 月 25 日
編集済み: Matt J 2013 年 10 月 25 日
Similarly, you could use a cell array and then post-concatenate
parfor i = 1:1000
x = rand();
if x > 0.5
B{i} = x;
end
end
B=cell2mat(B),

サインインしてコメントする。


Matlab2010
Matlab2010 2013 年 10 月 25 日
ok. perhaps the original example wasnt the best!
In my specific case B is a struct. with a very large number of fields. Hence generating each one is time consuming and thus why I want to use parfor.
How to use parfor when the output is a struct and you dont know the final number. Assignment is to a cell eg B{cnt} = struct()
  1 件のコメント
Matt J
Matt J 2013 年 10 月 25 日
Yes, you could do that,
parfor i = 1:1000
x = rand();
if x > 0.5
B{i}.field1=...;
B{i}.field2=...;
end
end
B=[B{:}];

サインインしてコメントする。


Matt J
Matt J 2013 年 10 月 25 日
Or, perhaps you meant something like this
fields = {'f1','f2','f3','f4'};
N=length(fields);
vals=cell(1,N);
parfor i = 1:N
switch fields{i}
case 'f1'
vals{i}=1;
otherwise
vals{i}=0;
end
end
args=[fields;vals];
B=struct(args{:})

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by