Trup
Trup

Reputation: 1655

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.

Upvotes: 11

Views: 64051

Answers (5)

hafiz
hafiz

Reputation: 11

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

ans =
     1     2
     5     6

Upvotes: -1

ZSzB
ZSzB

Reputation: 191

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.

Upvotes: 19

nooge9
nooge9

Reputation: 19

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'

Upvotes: 1

user933376
user933376

Reputation:

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

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

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476950

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

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

Upvotes: 23

Related Questions