a = [1 2; 3 4; 5 6]
I want to extract the first and third row of a
, so I have x = [1; 3]
(indices of rows).
a(x)
doesn't work.
In MATLAB if one parameter is given when indexing, it is so-called linear indexing. For example if you have 4x3 matrix, the linear indices of the elements look like this, they are growing by the columns:
1 5 9
2 6 10
3 7 11
4 8 12
Because you passed the [1 3] vector as a parameter, the 1st and 3rd elements were selected only.
When selecting whole columns or rows, the following format shall be used:
A(:, [list of columns]) % for whole columns
A([list of rows], :) % for whole rows
General form of 2d matrix indexing:
A([list of rows], [list of columns])
The result is the elements in the intersection of the indexed rows and columns. Results will be the elements marked by X:
A([2 4], [3 4 5 7])
. . C C C . C
R R X X X R X
. . C C C . C
R R X X X R X
Reference and some similar examples: tutorial on MATLAB matrix indexing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With