필터 지우기
필터 지우기

Delete all values in a row after the first value

조회 수: 2 (최근 30일)
FC93
FC93 2016년 10월 6일
댓글: FC93 2016년 10월 6일
Hi everyone
I have a matrix with 3000 rows and 4 columns. the values in the matrix are just one and zero. The sum of each row can just be one. In some rows the sum is 2. What I want now is to delete all 1 after the first 1. So in my matrix in each row I just want the first vaue 1 and all the following values in this matrix should be 0.
For example: row number 345: 0001000 1 0000 change to 0001000 0 0000
thank you for your help.

채택된 답변

KSSV
KSSV 2016년 10월 6일
m = 10 ; n = 5 ;
A = randi([0 1],m,n) ;
B = zeros(size(A)) ;
for i = 1:m
idx = find(A(i,:)==1) ;
B(i,idx(1))= 1;
end
There might be more elegant solution.
  댓글 수: 5
KSSV
KSSV 2016년 10월 6일
m=5540 , n=4
FOMC_X_try = zeros(size(FOMC_X));
for i = 1:m
idx = find(FOMC_X(i,:)==1) ;
if ~isempty(idx)
FOMC_X_try(i,idx(1))= 1;
end
end
If there are no ones in a particular row, idx will be empty. So is the error.
FC93
FC93 2016년 10월 6일
I replaced the old code with this one. Now it works. thank you very much for your help and your time.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 10월 6일
편집: Walter Roberson 2016년 10월 6일
B = cumsum(~cumprod(~A,2), 2) <= 1;
If I worked it out properly as I fall asleep...

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by