How to group values in a vector based on certain condition?
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
HARINI R
el 27 de Mzo. de 2022
Comentada: Voss
el 2 de Mayo de 2022
I have a row vector that has values 1 to 5 that keeps repeating like a cycle as following.
row = [1; 2; 3; 4; 5; 1; 1; 2; 3; 4; 5; 5; 1; 1; 2; 2; 3; 4; 5; 5]
I need to group this data taking 1 and 5 as reference. If the 1 or 5 is occuring more than once consecutively, consider the first 1 and last 5.
Ans =
[1 2 3 4 5 0 0 0;
1 1 2 3 4 5 5 0;
1 1 2 2 3 4 5 5 ]
Any ideas?
Thanks
0 comentarios
Respuesta aceptada
Voss
el 27 de Mzo. de 2022
If the sub-sequence always starts with a 1 and ends with a 5, you could do this:
row = [1; 2; 3; 4; 5; 1; 1; 2; 3; 4; 5; 5; 1; 1; 2; 2; 3; 4; 5; 5];
start_val = 1;
end_val = 5;
cycle_end_idx = [0; find(diff(row) == start_val-end_val); numel(row)]
n_cycles = numel(cycle_end_idx)-1;
cycle_length = diff(cycle_end_idx);
M = zeros(n_cycles,max(cycle_length));
for ii = 1:n_cycles
M(ii,1:cycle_length(ii)) = row(cycle_end_idx(ii)+1:cycle_end_idx(ii+1));
end
disp(M);
Ultimately, however, you may find that it's better to store those sub-sequences in a cell array rather than a matrix with extra zeros:
C = cell(1,n_cycles);
for ii = 1:n_cycles
C{ii} = row(cycle_end_idx(ii)+1:cycle_end_idx(ii+1)).';
end
format compact
celldisp(C);
6 comentarios
Voss
el 2 de Mayo de 2022
What should be the output for row = [0;1;1;2;2;3;4;5;0;1;2;3;4;5;5;0;1;1;2;4;5;0;1;2;3;4;5] with imposed cycle length (i.e., desired number of columns in output matrix) of 5?
Más respuestas (0)
Ver también
Categorías
Más información sobre Measurements and Feature Extraction 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!