MATLAB: Repeating elements (vector)

repeating elements

Hi everyone,
Suppose I have matrix A
A = [1; 2; 3; 4]
And I want to have matrix B
B = [1; 1; 2; 1; 2; 3; 1; 2; 3; 4]
I don't want to use loop to do so because I have lots of observations. So how can I do this efficiently without using loop? Thank you very much!
Jeff

Best Answer

There are most likely much more efficient algorithms than this:
>> N = 4;
>> X = (1:N)'*ones(1,N);
>> X(triu(true(N)))
ans =
1
1
2
1
2
3
1
2
3
4
You can use X as indices into your vector to select the values that you want.