フィルターのクリア

How to set all elements in a 2D Matrix between two indices to "1" in each row

2 ビュー (過去 30 日間)
Tim
Tim 2013 年 12 月 5 日
コメント済み: Tim 2013 年 12 月 6 日
I've a matrix A e.g. like this:
A =
1 0 0 1 0 0
0 0 1 0 0 1
0 1 1 0 0 0
0 1 0 1 0 0
And I want all elements between the "ones" per row to be "one" as well. The result should look like this: B =
1 1 1 1 0 0
0 0 1 1 1 1
0 1 1 0 0 0
0 1 1 1 0 0
If it helps, I also have two vectors with the indices of the first and second one.
Thanks!!
PS: If possible the solution would not use any loops since the real matrix that I have to use is very large and the program shall be very efficient.

採用された回答

Alfonso Nieto-Castanon
Alfonso Nieto-Castanon 2013 年 12 月 5 日
cumsum(A,2)==1|A;
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2013 年 12 月 5 日
+1
Tim
Tim 2013 年 12 月 6 日
A one liner..Perfect! Great work, thanks a lot!

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

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2013 年 12 月 5 日
cumsum(A,2)>0 & fliplr(cumsum(A(:,end:-1:1),2))>0
  2 件のコメント
Wayne King
Wayne King 2013 年 12 月 5 日
How you come up with some of these solutions Andrei! :)
Tim
Tim 2013 年 12 月 6 日
Nice Solution as well! Thanks!

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


sixwwwwww
sixwwwwww 2013 年 12 月 5 日
you can do it as follow:
for i = 1:size(A, 1)
idx = find(A(i, :));
A(i, min(idx):max(idx)) = 1;
end
  1 件のコメント
Tim
Tim 2013 年 12 月 5 日
Nice, thanks! That helps. But is there a way to avoid the loop? E.g. use a vector that contains all the "idx" or so? Thanks!

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by