how to velocize it (avoid loop is possible)

1 回表示 (過去 30 日間)
Luca Re
Luca Re 2024 年 2 月 3 日
コメント済み: Matt J 2024 年 2 月 4 日
E=[0 5 6 9 2;0 0 1 3 1;0 5 4 2 4]'
E = 5×3
0 0 0 5 0 5 6 1 4 9 3 2 2 1 4
filtro=ones(size(E));
for i=1:width(E)
bu=find(E(:,i),1,'first');
filtro(1:bu,i)=0;
end
filtro
filtro = 5×3
0 0 0 0 0 0 1 0 1 1 1 1 1 1 1

採用された回答

Matt J
Matt J 2024 年 2 月 3 日
編集済み: Matt J 2024 年 2 月 4 日
E=[0 5 6 9 2;0 0 1 3 1;0 5 4 2 4]';
[~,I]=max(logical(E),[],1);
filtro=(1:height(E))'>I
filtro = 5×3 logical array
0 0 0 0 0 0 1 0 1 1 1 1 1 1 1

その他の回答 (1 件)

Catalytic
Catalytic 2024 年 2 月 4 日
I don't know if "velocize" (not a word) is supposed to mean "accelerate" or "vectorize". The two are not the same.
If you're looking for the fastest possible code, there's no way to know in advance because it depends on the sparsity of E. For very dense E, your loop will probably be faster than @Matt J's answer.
E=rand(5000,3000)>0.1;
tic
filtro=true(size(E));
for i=1:width(E)
bu=find(E(:,i),1,'first');
filtro(1:bu,i)=0;
end
toc
Elapsed time is 0.016652 seconds.
tic
[~,I]=max(logical(E),[],1);
filtro=(1:height(E))'>I;
toc
Elapsed time is 0.031441 seconds.
  1 件のコメント
Matt J
Matt J 2024 年 2 月 4 日
True, but be mindful of the flipside:
E=rand(5000,3000)>0.7;
tic
filtro=true(size(E));
for i=1:width(E)
bu=find(E(:,i),1,'first');
filtro(1:bu,i)=0;
end
toc
Elapsed time is 0.051811 seconds.
tic
[~,I]=max(logical(E),[],1);
filtro=(1:height(E))'>I;
toc
Elapsed time is 0.020633 seconds.

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

カテゴリ

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