MATLAB - extracting rows of a matrix

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.

Answers


Like this: a([1,3],:)

The comma separates the dimensions, : means "entire range", and square brackets make a list.


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.


x = a([1 3]) behaves like this:

temp = a(:)     % convert matrix 'a' into a column wise vector
x = temp([1 3]) % get the 1st and 3rd elements of 'a'

you could write a loop to iterate across the rows of the matrix:

for i = [1,3]
    a(i,:)
end

type this: a([1 3],[1 2]) the output is

ans =
     1     2
     5     6

Need Your Help

How can I get relative path of the folders in my android project?

java android eclipse resources

How can I get the relative path of the folders in my project using code?

Shared Memory between two JVMs

java memory-management jvm

Is there a way in JAVA, for two JVMs (running on same physical machine), to use/share the same mermory address space? Suppose a producer in JVM1 puts messages at a particular pre-defined memory loc...