Make array with elements repeating as many times as specified in another list.
Show older comments
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 Comment
atharva aalok
on 14 Aug 2023
Edited: atharva aalok
on 14 Aug 2023
Accepted Answer
More Answers (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
on 14 Aug 2023
Edited: Chetan Bhavsar
on 14 Aug 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
Categories
Find more on Sequence and Numeric Feature Data Workflows in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!