Make array with elements repeating as many times as specified in another list.
Mostrar comentarios más antiguos
I have a cell array of vectors, where each vector is of a different length. Something like (but much larger):
a{1} = [1, 2, 4];
a{2} = [5, 3, 8, 9];
a{3} = [2, 6, 3, 7, 8, 1];
I want to create a new array where 1s are repeated as many times as length of a{1}, 2s are repeated as many times as length of a{2} and so on.
I am currently using a loop to do this as:
% Vector of sequence of 1s, 2s etc.
y_val = [];
for k = 1: length(a)
y_val = [y_val, k * ones(1, length(a{k}))];
end
Is there a faster way of doing this?
The actual variables in my code are much larger. Thus, I want the fastest way of solving this.
(I have access to all the toolboxes in matlab)
Note: I also have access to a vector a_lengths, in which a_lengths(i) is the length of a{i}.
1 comentario
atharva aalok
el 14 de Ag. de 2023
Editada: atharva aalok
el 14 de Ag. de 2023
Respuesta aceptada
Más respuestas (2)
a{1} = [1, 2, 4];
a{2} = [5, 3, 8, 9];
a{3} = [2, 6, 3, 7, 8, 1];
y_val = repelem(1:length(a), cellfun('length', a))
Chetan Bhavsar
el 14 de Ag. de 2023
Editada: Chetan Bhavsar
el 14 de Ag. de 2023
a{1} = [1, 2, 4];
a{2} = [5, 3, 8, 9];
a{3} = [2, 6, 3, 7, 8, 1];
tic
% Vector of sequence of 1s, 2s etc.
y_val = [];
for k = 1: length(a)
y_val = [y_val, k * ones(1, length(a{k}))];
end
disp(y_val)
toc
tic
cell_lengths = cellfun(@length, a);
y_val = arrayfun(@(k) k * ones(1, cell_lengths(k)), 1:length(a), 'UniformOutput', false);
y_val = [y_val{:}]; % Convert from cell to array
disp(y_val)
toc
Categorías
Más información sobre Sequence and Numeric Feature Data Workflows en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!