Because of the dynamic nature of B
, there is no way you can do it without any loops. I would not shy away from loops in this case - especially for more recent versions of MATLAB with their improved JIT compiler. Loops are now quite competitive over vectorized operations depending on what exactly you want to do.
The easiest approach would be to loop over all values of A
and the colon operator and go from 1
up to each value in A
.
Something like this would work:
A = [1; 2; 3; 4];
B = [];
for v = 1 : numel(A)
B = [B; (1:A(v)).'];
end
At each iteration, we find a value in A
and create a vector that goes from 1 up to the value. We concatenate all of these into a single vector. Keep in mind that no error checking is performed so we're assuming that every value in A
is greater than or equal to 1.
If you're keen on a one liner, it's possible to do this with arrayfun
to create a bunch of cell arrays and squeeze them together, but performance wise this may not be the best solution:
A = [1; 2; 3; 4];
B = cell2mat(arrayfun(@(x) (1:x).', A, 'un', 0));
arrayfun
takes in a function to operate on each input element in A
, so the function would be to create a column vector from 1 up to the desired value. un
is short for UniformOutput
and it is set to 0 meaning that the output is not uniform, so we're going to output a bunch of cell arrays - one for each vector you've created. Finally, cell2mat
squeezes all of the cell arrays together to create a single column vector. It's more elegant, but performance wise it may not be so as there is a lot of overhead.