how to slice variables to use parfor
5 次查看(过去 30 天)
显示 更早的评论
Hi,
I cannot convert this for loop into a parfor loop: I tried to have a look to the help but I cannot understand how to slice this variable to use the parfor istead of the for loop.
tot_rows = randi([10000,20000],1);
tot_cols = randi([10,500],1);
data = zeros(tot_rows, tot_cols);
for k=1:tot_cols
idx = randi([1 tot_rows], randi([1 tot_rows]), 1); %now is generated randomly, then in real version idx is found with a criteria...
tmp = rand(length(idx),1);%now is generated randomly, then in real version tmp is taken from txt file...
data(idx,k) = tmp;
end
If I try to use the parfor loop I get the following error, I suppose because "data" array cannot be recalled in this way but I cannot understand how to slice it:
tot_rows = randi([10000,20000],1);
tot_cols = randi([10,500],1);
data = zeros(tot_rows, tot_cols);
parfor k=1:tot_cols
idx = randi([1 tot_rows], randi([1 tot_rows]), 1); %now is generated randomly, then in real version idx is found with a criteria...
tmp = rand(length(idx),1);%now is generated randomly, then in real version tmp is taken from txt file...
data(idx,k) = tmp;
end
Error using test_for (line 6)
Error: Unable to classify the variable 'data' in the body of the parfor-loop. For more information, see Parallel for Loops in MATLAB, "Solve Variable Classification Issues in parfor-Loops".
Thanks everyone for the help! :)
0 个评论
采纳的回答
Matt J
2021-3-20
编辑:Matt J
2021-3-20
One way,
[I,J,S]=deal(cell(tot_cols,1));
parfor k=1:tot_cols
idx = randi([1 tot_rows], randi([1 tot_rows]), 1); %now is generated randomly, then in real version idx is found with a criteria...
tmp = rand(length(idx),1);%now is generated randomly, then in real version tmp is taken from txt file...
[I{k} ,J{k},S{k}]=deal(idx,idx,tmp);
J{k}(:)=k;
end
data = accumarray(cell2mat([I,J]), cell2mat(S),[tot_rows, tot_cols]);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!