How to replace two nested for with vectorization

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 Kommentare

KSSV
KSSV am 29 Mär. 2016
Are you sure that AC in the above is an array?
etudiant_is
etudiant_is am 29 Mär. 2016
AC is a vector not an array
KSSV
KSSV am 29 Mär. 2016
It's dimension is equal to i.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 29 Mär. 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')

Weitere Antworten (0)

Kategorien

Mehr zu Language Fundamentals finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by