Borrar filtros
Borrar filtros

Sequence of a specific number in a matrix

2 visualizaciones (últimos 30 días)
Jonas Damsbo
Jonas Damsbo el 3 de En. de 2019
Respondida: Star Strider el 3 de En. de 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?

Respuesta aceptada

Star Strider
Star Strider el 3 de En. de 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’.

Más respuestas (0)

Categorías

Más información sobre Numeric Types en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by