How to replace two nested for with vectorization

2 ビュー (過去 30 日間)
etudiant_is
etudiant_is 2016 年 3 月 29 日
コメント済み: etudiant_is 2016 年 3 月 29 日
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 件のコメント
etudiant_is
etudiant_is 2016 年 3 月 29 日
AC is a vector not an array
KSSV
KSSV 2016 年 3 月 29 日
It's dimension is equal to i.

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2016 年 3 月 29 日
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')
  1 件のコメント
etudiant_is
etudiant_is 2016 年 3 月 29 日
yes AC has been initialized previously

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLanguage Fundamentals についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by