How to vectorize this code to eliminate nested For loops

1 回表示 (過去 30 日間)
Jae Min Lee
Jae Min Lee 2018 年 9 月 4 日
コメント済み: Jae Min Lee 2018 年 9 月 4 日
Would like to know how this code be vectorized:
for y=1:rows
for x=1:cols
if (segMat(y,x) == 255)
Energy(y,x) = Energy(y,x) + motionMap(y,x);
end
end
for y=1:rows
for x=1:cols
delta(y,x) = kronDel(255, segMat(y,x));
end
end
The kronDel function acts like the Kronecker delta.
  2 件のコメント
Rik
Rik 2018 年 9 月 4 日
Is segMat a function or an array? The second set of loops could be replaced with a call to arrayfun, but this is not always a speed improvement.
Jae Min Lee
Jae Min Lee 2018 年 9 月 4 日
編集済み: Jae Min Lee 2018 年 9 月 4 日
segMat is an image array.

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

採用された回答

Walter Roberson
Walter Roberson 2018 年 9 月 4 日
編集済み: Walter Roberson 2018 年 9 月 4 日
Assuming that motionMap is an array and not a function,
%no loop needed
mask = segMat == 255;
Energy(mask) = Energy(mask) + motionMap(mask);
After which you can have the second nested loop calling kronDel
kronDel looks more likely to be a function than an array, so it is difficult to know if we could vectorize that section.
I speculate that your kronDel function returns the first parameter if the second parameter is 0, and otherwise returns 0. If my speculation is correct, then the loops and call could be replaced by
delta = 255 .* (segMat == 0);

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by