MATLAB: copy a specific portion of an array

matlabmatrix

I am trying to copy a few elements from a matrix, but not a whole row, and not a single element.

For example, in the following matrix:

a = 1 2
    3 4
    5 6
    7 8
    9 0

How would I copy out just the following data?

b = 1
    3
    5

i.e. rows 1:3 in column 1 only… I know that you can remove an entire column like this:

b = a(:,1)

… and I appreciate that could just do this and then dump the last two rows, but I'd like to use more streamlined code as I am running a very resource-intensive solution.

Best Solution

Elements in a matrix in MATLAB are stored in column-major order. Which means, you could even use a single index and say:

b = a(1:3);

Since the first 3 elements ARE 1,3,5. Similarly, a(6) is 2, a(7) is 4 etc. Look at the sub2ind method to understand more:

http://www.mathworks.com/help/techdoc/ref/sub2ind.html