Sequence of a specific number in a matrix
2 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!