How to replace two nested for with vectorization
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
etudiant_is
il 29 Mar 2016
Commentato: etudiant_is
il 29 Mar 2016
How can I write this without loops
[nrows, ncols] = size(A);
for i = 1:nrows
for j = 1:ncols
if A(i,j)~=0
AC(i) = AC(i)+C(i,A(i,j));
else
break
end
end
end
3 Commenti
Risposta accettata
Walter Roberson
il 29 Mar 2016
maxA = max(A(:));
Ccopy = C;
Ccopy(:,maxA+1) = 0;
A(A==0) = maxA+1;
for i = 1 : nrows
AC(i) = sum( C(sub2ind(size(C), 1:nrows, A(:,j))) );
end
Provided that in code before what was posted, AC was initialized to 0's. If AC was not initialized then replace the code with
error('This is the vectorized equivalent to broken code')
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Language Fundamentals in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!