Vectorize "for"-loop in multidimentional array

1 回表示 (過去 30 日間)
Zhakshylyk Nurlanov
Zhakshylyk Nurlanov 2020 年 11 月 16 日
回答済み: Steve Eddins 2020 年 11 月 16 日
I would like to vectorize the following for-loop. Is it possible and how?
Y = ones(n, L, L)
% size(x_i_left) = (n , 1)
for i=1:n
Y(i, 1:x_i_left(i), :) = 0;
Y(i, x_i_right(i):end, :) = 0;
Y(i, :, 1:x_j_left(i)) = 0;
Y(i, :, x_j_right(i):end) = 0;
end

回答 (1 件)

Steve Eddins
Steve Eddins 2020 年 11 月 16 日
It is conceivable that the loop might be eliminated with some sub2ind calculations followed by linear indexing, but I would expect that to be slower and take more more memory than the loop you have written. Why do you want to eliminate the loop?
If I understand your code correctly, then I think it could be simplified to something like this:
Y = zeros(n,L,L);
for i = 1:n
Y(i, (x_i_left(i)+1):(x_i_right(i)-1), (x_j_left(i)+1):(x_j_right(i)-1)) = 1;
end
I expect that this would execute faster.

カテゴリ

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