% Allocate cell array
cell_array_length = 2000;
a_lengths = randi([5000, 10000], 1, cell_array_length);
for i = 1: cell_array_length
a{i} = rand(1, a_lengths(i));
end
% My code
tic
% Vector of sequence of 1s, 2s etc.
y_val_my = [];
for k = 1: length(a)
y_val_my = [y_val_my, k * ones(1, length(a{k}))];
end
toc
Elapsed time is 53.341348 seconds.
% My Other code
tic
y_val_myother = zeros(1, sum(a_lengths));
idx_list = [0, cumsum(a_lengths)];
for k = 1: length(a)
y_val_myother(idx_list(k)+1: idx_list(k+1)) = k;
end
toc
Elapsed time is 0.053105 seconds.
% Bruno's Code
tic
y_val_bruno = repelem(1:length(a), cellfun('length', a));
toc
Elapsed time is 0.023451 seconds.
% Chetan's Code
tic
cell_lengths = cellfun(@length, a);
y_val = arrayfun(@(k) k * ones(1, cell_lengths(k)), 1:length(a), 'UniformOutput', false);
y_val_chetan = [y_val{:}]; % Convert from cell to array
toc
Elapsed time is 0.104331 seconds.
% Walter (Bruno's code + known lengths of vectors)
tic
y_val_walter = repelem(1:length(a), a_lengths);
toc
Elapsed time is 0.023355 seconds.
% disp(y_val_my);
% disp(y_val_myother);
% disp(y_val_bruno);
% disp(y_val_chetan);
% disp(y_val_walter);