Make array with elements repeating as many times as specified in another list.
显示 更早的评论
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 个评论
采纳的回答
更多回答(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))
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
类别
在 帮助中心 和 File Exchange 中查找有关 Multirate Signal Processing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!