Filter löschen
Filter löschen

Sequence of a specific number in a matrix

2 Ansichten (letzte 30 Tage)
Jonas Damsbo
Jonas Damsbo am 3 Jan. 2019
Beantwortet: Star Strider am 3 Jan. 2019
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?

Akzeptierte Antwort

Star Strider
Star Strider am 3 Jan. 2019
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’.

Weitere Antworten (0)

Kategorien

Mehr zu Numeric Types finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by