1
 0     0     1     1
 1     1     2     2
 2     2     3     3
 3     3     4     4
 4     4     5     5

I want to make matrix like above without for loops. I only know how to do it with a loop. This is my code

x = [0 0 1 1];
for i = 1:4   
    x= [x;x(1,:)+i]
end

Is there a way in a vector like function ':'? Or in other ways. I want to know how to insert an increased element value into a matrix row without loop.

Dam baba
  • 13
  • 2

4 Answers4

3

You could use bsxfun:

result = bsxfun(@plus,x,(0:4).')

In Matlab 2016b or newer you can also directly expand singleton dimensions:

result = x + (0:4).'
Leander Moesinger
  • 2,449
  • 15
  • 28
1

You can also use cumsum to cumulatively sum down the columns. So create your starting vector, with a matrix of ones underneath for the other rows.

cumsum([0 0 1 1; ones(4,4)]) % ones(n-1, 4) for result with n rows, input 4 columns

This has the advantage of being able to do other step sizes easily

cumsum([0 0 1 1; 2*ones(4,4)]) % steps of 2

Furthermore, it can handle different intervals in each column if we employ repmat

% Row one ↓   interval per col ↓   
cumsum([0 0 1 1; repmat([1 2 3 4], 4, 1)]); % Again, use n-1 in place of 4
Wolfie
  • 27,562
  • 7
  • 28
  • 55
0

If you vertically concatenate the row vectors you want and then take the transpose you will get the required result (ie x=[0:4;0:4;1:5;1:5]' in this example).

etmuse
  • 505
  • 2
  • 9
  • This only seems *less* flexible that the original method... always try and assume examples given like this are simplifications of what the OP wants to achieve – Wolfie Sep 28 '17 at 13:47
  • Depends what type of flexibility you want - if each column needed to increment by a different uniform number then this would be easier than in the original. I'm not saying it's the best solution, but the whole beauty of SO is that not every answer offered needs to be the best one (and hopefully the best one will eventually become apparent). – etmuse Sep 28 '17 at 14:03
0

You can use kron + one of methods suggested here.

kron(hankel(0:4,4:5),[1 1])
rahnema1
  • 15,264
  • 3
  • 15
  • 27