Reputation: 6531
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?
Upvotes: 12
Views: 33993
Reputation: 31
This operator tells matlab to try to convert the data type also.
For example:
Both data types set as disparate types:
>> foo = uint8(0);
>> bar = double(0);
Check data types with "whos" command:
>> whos foo bar
Name Size Bytes Class Attributes
bar 1x1 8 double
foo 1x1 1 uint8
Assign the uint8 into the double with the (:) operator:
>> bar(:) = foo;
and it remains a double
>> whos foo bar
Name Size Bytes Class Attributes
bar 1x1 8 double
foo 1x1 1 uint8
assign the double with a unit8 without the (:) operator :
>> bar = foo;
and it changes to a uint8 data type:
>> whos foo bar
Name Size Bytes Class Attributes
bar 1x1 8 uint8
foo 1x1 1 uint8
Upvotes: 1
Reputation: 75
If x is a matrix, like the following: a 3*3 matrix,
x=[1,2,3;4,5,6;7,8,9];
x=x(:);
The statement x=x(:) lists the matrix as a column vector. The output would be
1
2
3
4
5
6
7
8
9
The same is what is obtained when x is a row vector.
so in general, x(:) lists the elements of x as column vector.
Upvotes: 1
Reputation:
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.
Upvotes: 2
Reputation: 236034
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(:)'
Upvotes: 2
Reputation: 14446
x(:)
reshapes your matrix.
Thereby, if your matrix is
1 2 3
5 6 7
8 9 10
calling x=x(:)
sets x
to
1
5
8
2
6
9
3
7
10
Upvotes: 1
Reputation: 272557
:
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(:);
disp(x)
results in:
1
2
3
4
Upvotes: 15