Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The matrix indexing outputs of x(:) and x(1:end) are different

The following is test code and their matrix indexing outputs respectively. Aren't x(:) and x(1:end) the same thing in MATLAB? Why are their outputs different?

>>x = [1 2 3;4 5 6]
x =
     1     2     3
     4     5     6
>> xx = x(:)
xx =
     1
     4
     2
     5
     3
     6
>> xx = x(1:end)
xx =
     1     4     2     5     3     6
like image 490
livemyaerodream Avatar asked Mar 05 '23 08:03

livemyaerodream


1 Answers

There are many different ways to index in MATLAB. This question deals with two of those modes. In short, x(:) is not a short-cut to x(1:end).

x(1:end) is equivalent to x(1:numel(x)), which in this case is x(1:6). p=1:6 is a row vector with indices. Here we are telling MATLAB to create a new row vector where each element i corresponds to x(p(i)). Doing x((1:6).') will yield a column vector, because the indexing array is a column vector. x([1,2;3,4;5,6]) will yield a 3x2 matrix, because the indexing array is a 3x2 matrix.

x(:) tells MATLAB to reshape the array x into a column vector. It is equivalent to reshape(x,[],1).

like image 173
Cris Luengo Avatar answered Mar 16 '23 06:03

Cris Luengo