Effacer les filtres
Effacer les filtres

how to slice variables to use parfor

3 vues (au cours des 30 derniers jours)
endystrike
endystrike le 20 Mar 2021
Commenté : endystrike le 20 Mar 2021
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! :)

Réponse acceptée

Matt J
Matt J le 20 Mar 2021
Modifié(e) : Matt J le 20 Mar 2021
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]);
  1 commentaire
endystrike
endystrike le 20 Mar 2021
thx a lot Sir! :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Parallel for-Loops (parfor) dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by