Assuming I have the following matrices/vectors
A=[1 3 0
2 0 0
4 5 6];
B=[111
222
333];
C=[10 5 20 25 3 7
1 2 4 6 8 12
11 22 33 44 55 66] ;
I=[0 1 0 0 1 1
1 1 1 1 1 0
0 0 0 0 0 0] ;
D and E are also initialized to 0 before the loops
I have to following 3 nested loops that I want to replace/vectorize. How can I do it?
[nrows, ncols]= size(A);
E=zeros(nnz(A),1);
D=zeros(nnz(A),nrows);
for i = 1:nrows
for j = 1:ncols
if A(i,j)~=0
Id=A(i,j);
E(Id)=C(i,Id)+ B(i);
[p,~] =find(I(:,Id)~=0);
for k=p
D(Id,k)=C(k,Id)+(B(k)+1);
end
else
break
end
end
end

4 commentaires

Stephen23
Stephen23 le 11 Mai 2016
Modifié(e) : Stephen23 le 11 Mai 2016
When I use those matrices and that code I get this error:
Subscripted assignment dimension mismatch.
Error in Untitled3 (line 38)
D(Id,m)=C(k,Id)+(B(k)+1);
etudiant_is
etudiant_is le 11 Mai 2016
You are right, I had a mistake in my example. I edited the question, now the loops run fine.
Matt J
Matt J le 11 Mai 2016
Are the non-zero values of A always distinct?
etudiant_is
etudiant_is le 11 Mai 2016
Modifié(e) : etudiant_is le 11 Mai 2016
yes, they can not be present more than once in A.

Connectez-vous pour commenter.

 Réponse acceptée

Matt J
Matt J le 11 Mai 2016
Modifié(e) : Matt J le 11 Mai 2016

1 vote

[ma,na]=size(A);
nnza=nnz(A);
[mc,nc]=size(C);
[mi,ni]=size(I);
[i,j,Id]=find(A);
k=sub2ind([ma,nc],i,Id);
E=sum(accumarray([i,Id],C(k)+B(i)) ,1).',
IA=bsxfun(@times,I,nonzeros(A).');
[i,j,Id]=find(IA);
k=sub2ind([mi,nc],i,Id);
D=accumarray([i,Id],C(k)+B(i)+1,[ma,nnza]).'

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by