From: Camron Call on
I want to index a matrix by index pairs.

row = [5 2 3 5 1];
col = [1 2 3 4 5];

a = magic(5);

%gives a 5 by 5 since each row is paired with each col
a(row,col)

% I would like to get the following without writing it out or looping if possible

b = [a(row(1),col(1)), a(row(2),col(2)), a(row(3),col(3)), a(row(4),col(4)), a(row(5),col(5))]

thanks
From: Walter Roberson on
Camron Call wrote:
> I want to index a matrix by index pairs.
> row = [5 2 3 5 1];
> col = [1 2 3 4 5];
>
> a = magic(5);
>
> %gives a 5 by 5 since each row is paired with each col
> a(row,col)
> % I would like to get the following without writing it out or looping if
> possible
>
> b = [a(row(1),col(1)), a(row(2),col(2)), a(row(3),col(3)),
> a(row(4),col(4)), a(row(5),col(5))]

a(sub2ind(size(a),row,col))
From: reza on
On Jul 30, 2:59 pm, "Camron Call" <camronc...(a)gmail.cam> wrote:
> I want to index a matrix by index pairs.  
Slightly less elegant way:

arrayfun(@(x,y) a(x,y), row, col)

/m

>
> row = [5 2 3 5 1];
> col = [1 2 3 4 5];
>
> a = magic(5);
>
> %gives a 5 by 5 since each row is paired with each col
> a(row,col)  
>
> % I would like to get the following without writing it out or looping if possible
>
> b = [a(row(1),col(1)), a(row(2),col(2)), a(row(3),col(3)), a(row(4),col(4)), a(row(5),col(5))]
>
> thanks