필터 지우기
필터 지우기

Sequence of a specific number in a matrix

조회 수: 2 (최근 30일)
Jonas Damsbo
Jonas Damsbo 2019년 1월 3일
답변: Star Strider 2019년 1월 3일
Hey
So my trouble is that I have a matrix, here a an example becuase my original matrix is really big.
0 1 1 1 0
0 1 0 1 1
1 1 0 0 0
1 1 1 0 1
0 1 1 1 1
Now I want the sequences of 1 in each row so I get something like:
3
1 2
2
3 1
4
It is possible?

채택된 답변

Star Strider
Star Strider 2019년 1월 3일
Try this:
M = [ 0 1 1 1 0
0 1 0 1 1
1 1 0 0 0
1 1 1 0 1
0 1 1 1 1];
dM = diff([zeros(size(M(:,1))), M, zeros(size(M(:,1)))], 1, 2);
for k1 = 1:size(M,1)
first = strfind(dM(k1,:), 1);
last = strfind(dM(k1,:), -1);
dif{k1,:} = last - first;
end
cols = max(cellfun(@(x)size(x,2), dif));
Result = zeros(size(M,1),cols);
for k1 = 1:size(M,1)
Result(k1,1:numel(dif{k1})) = dif{k1};
end
producing
Result =
3 0
1 2
2 0
3 1
4 0
The actual output is in the ‘dif’ cell array. The code after that and the second loop simply converts it to a double array I call ‘Result’.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by