Select and remove/replace values in matrix

My question is to check each row for the same numbers (in this case 1 or 0, we leave the 0s unchanged in the matrix), and replace any 1 in the row with 0 except the last value of 1
Y = [0 1 1 0 1 0;
0 0 0 1 0 1;
1 0 1 0 1 0; ]
The end result I should get is
X = [0 0 0 0 1 0;
0 0 0 0 0 1;
0 0 0 0 1 0;]
Another similar question would be to remover the first/second (sometimes even third) number in the row leaving the last 2 numbers unchanged.
Y = [1 2 4 0 0 0;
2 5 0 0 0 0;
3 4 5 6 0 0;]
The end result I should get is
X = [0 2 4 0 0 0;
2 5 0 0 0 0;
0 0 5 6 0 0;]

 採用された回答

Guillaume
Guillaume 2019 年 7 月 23 日
編集済み: Guillaume 2019 年 7 月 23 日

2 投票

One way:
nelems = 2; %number of elements to keep
X = (cumsum(Y>0, 2, 'reverse') < nelems+1) .* Y

6 件のコメント

JL
JL 2019 年 7 月 23 日
I have tried it but it gives me the below answer:
X =
0 0 1 0 1 0
0 0 0 1 0 1
0 0 1 0 1 0
I'm trying to get something like this below:
X =
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 1 0
JL
JL 2019 年 7 月 23 日
It is working for both problems! Thank you very much - i just checked again!
JL
JL 2019 年 7 月 24 日
編集済み: Guillaume 2019 年 7 月 24 日
I have another follow up question please. If I have introduced Z
Z = [2;
0;
15;]
to this matrix
X =
[ 0 0 1 0 1 0;
0 0 0 1 0 1;
0 0 1 0 1 0;]
where we only replace 1 with 0 if Z is >0 with that
Y =
[ 0 0 0 0 1 0;
0 0 0 1 0 1;
0 0 0 0 1 0;]
Guillaume
Guillaume 2019 年 7 月 24 日
Probably, the simplest is to use the same as before, then reinsert the original rows when Z is 0:
nelems = 1; %number of elements to keep
Y = (cumsum(X>0, 2, 'reverse') < nelems+1) .* X;
Y(Z == 0, :) = X(Z == 0, :)
JL
JL 2019 年 7 月 24 日
Thank you, it is working!
JL
JL 2019 年 8 月 8 日
Hi Guillaumen, I have another intetesting problem, was wondering if you are interested to take a look - here is the link to the question https://uk.mathworks.com/matlabcentral/answers/475460-sharing-values-of-elements-in-a-matrix

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

その他の回答 (0 件)

タグ

質問済み:

JL
2019 年 7 月 23 日

コメント済み:

JL
2019 年 8 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by