Take the 2-minute tour ×

This is a hard question to google. I am new to Matlab and have seen the following statement, but I can't see how it does anything. What doe x = x(:) do?

share|improve this question
add comment

5 Answers

up vote 8 down vote accepted

: is the colon operator. In this context, it reshapes x to a one-dimensional column vector.

So this code:

x = [ 1 3
      2 4 ];

x = x(:);


results in:

share|improve this answer
Do you know if it just does a reshape (so will copy on write) or forces a copy at that point (even if x is already a column)? –  robince Jan 17 '12 at 9:29
@robince: Good question. I'd like to think that x(:) is exactly equivalent to reshape(x, [], 1). But I don't know for sure (I'm not sure this is documented anywhere). I suppose one could try to figure it out via profiling. –  Oli Charlesworth Jan 17 '12 at 10:11
Yes I checked and seems to have normal copy on write semantis (with 2011b). I don't know why I had the idea it forced a copy - perhaps it did some time in the past. –  robince Jan 18 '12 at 10:39
add comment

x(:) transforms the array to a column vector.

More about the colon operator

share|improve this answer
and it's actually not that hard to google. –  pjotr Jan 15 '12 at 2:39
add comment

This syntax is generally used to ensure that x is a column vector:

x = x(:)

Similarly, this line ensures that x is a row vector

x = x(:)'
share|improve this answer
add comment

x(:) reshapes your matrix.

Thereby, if your matrix is

1 2 3
5 6 7
8 9 10

calling x=x(:) sets x to

share|improve this answer
add comment

As others have said, x(:) converts x into a vector, a column vector specifically. The point is that it makes your code robust to the user supplying a row vector my accident. For example,

x = 1:5;

has created a ROW vector. Some operations will require a column vector. Since x(:) does nothing to a vector that is already a column vector, this is a way of writing robust, stable code.

Of course, if x was a 3x4 matrix, it will still convert x into a column vector of length 12, so the best code needs to test for things like that, if it is a problem.

share|improve this answer
add comment

Your Answer


