Effacer les filtres
Effacer les filtres

Sequence of a specific number in a matrix

2 vues (au cours des 30 derniers jours)
Jonas Damsbo
Jonas Damsbo le 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?

Réponse acceptée

Star Strider
Star Strider le 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’.

Plus de réponses (0)

Catégories

En savoir plus sur Numeric Types dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by