Using nested for loops inside parfor

1 回表示 (過去 30 日間)
Louis
Louis 2014 年 12 月 2 日
コメント済み: Louis 2014 年 12 月 2 日
Hi,
I have upper triangle portion of n by n matrix to fill with s sample values (consider undirected and fully connected network without repeating edges). Sample values are drawn from designated pools unique to each entry of the upper triangle. For the simplicity, I am just putting in random values in the sample code below. Since I am taking a very large number of samples, and this is the major bottleneck in running time, I have decided to use parfor. However, I keep getting this error message saying "The PARFOR loop cannot run due to the way variable 'a' is used". I have read parfor documentation several times and understood required structures, sliced variables, and etc, but I can't figure this out. Any help would be greatly appreciated! Thanks,
%Create the matrix and assign preallocate zeros on the upper triangle portion to fill with sample values
matrix = cell(n,n);
for i = 1:n
for j = i+1:n
a{i,j} = zeros(s,1);
end
end
parfor k = 1:s
for i = 1:n
for j = i+1:n
a{i,j}(k) = rand; %Instead of rand there will be some specific function
end
end
end

採用された回答

Guillaume
Guillaume 2014 年 12 月 2 日
編集済み: Guillaume 2014 年 12 月 2 日
In the statement
A{i, j}(k) = something
with k scalar, something has to be scalar for it to work. So, you could just as well do:
parfor k = 1:s
a{k} = zeros(n);
for i = 1:n
for j=i+1:n
a{k}(i,j) = rand; %or whatever scalar is returned by your function
end
end
end
a = cat(3, a{:}) %3d matrix rather than cell array
If you really want a cell array at the end, after the cat:
a = num2cell(a, 3);
  1 件のコメント
Louis
Louis 2014 年 12 月 2 日
Thank you. This works!

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

その他の回答 (1 件)

Matt J
Matt J 2014 年 12 月 2 日
編集済み: Matt J 2014 年 12 月 2 日
I agree the documentation doesn't make it obvious what the problem is. But I think the problem is you are trying to slice a variable in the 2nd level of indexing. One fix, at least for the example you've shown, is to make "a" into a 3D numeric array instead of a cell array,
a=zeros(s,n,n);
parfor k = 1:s
for i = 1:n
for j = i+1:n
a(k,i,j)=rand;
end
end
end
a=num2cell(a,1); %post-convert to cell if needed
  3 件のコメント
Matt J
Matt J 2014 年 12 月 2 日
This appears to fix it.
parfor k = 1:100
for i = 1:10
for j = 1:10
if j>=i+1
a(k,i,j) = rand;
end
end
end
end
Louis
Louis 2014 年 12 月 2 日
Thank you!

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

カテゴリ

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