I want to add a fixed number of sequential numbers to every element in the array.
Eg: If array = [32 67 9]
and the fixed number, k = 3;
output = [32 33 34 35 67 68 69 70 9 10 11 12];
Here the 3 numbers following 32 are added after 32 and then the same is done to rest of elements in array.
Please note that the array length will be different each time.
For older MATLAB version (w/o explicit expansion):
function out = q53920251(input, k)
out = reshape( ...
bsxfun(@plus, input(:).', reshape(0:k, [], 1)), ...
1, []);
In newer versions (which allow a shorter syntax):
out = reshape( (0:k).' + array, 1, []);
The way the above vectorized solutions work is by "adding" the column vector of 0:k
to the row vector which is the input array. This operation expands both of the vectors to be the correct size, then performs the summation per-element, sort of like what you get from this:
[XX,YY] = ndgrid(0:k, arr);
%{
XX =
0 0 0
1 1 1
2 2 2
3 3 3
YY =
32 67 9
32 67 9
32 67 9
32 67 9
%}
tmp = XX + YY;
Both of the solutions above create the same array as tmp
intermediately,
tmp =
32 67 9
33 68 10
34 69 11
35 70 12
and then what's left is just to reorganize the elements into a row vector, using reshape
.