Chenming Zhang
Chenming Zhang

Reputation: 2566

matlab get data from a matrix with data row and column indeces stored in arrays

given the data matrix and indeces arrays for rows and columns

data=reshape(1:9,3,3)
row_index=[1,2,3];
column_index=[1,2,2];

I can get result=[1,5,6] by

for i =1:length(row_index)
   result(i)=data(row_index(i),column_index(i));
end

How to vectorize the loop?

Upvotes: 2

Views: 60

Answers (2)

Chenming Zhang
Chenming Zhang

Reputation: 2566

I also find a indirect way without using.

data(column_index*size(data,2)+row_index)

Upvotes: 1

P0W
P0W

Reputation: 47794

Like this : ( using sub2ind )

indices = sub2ind( size(data), row_index, column_index );

Then,

result = data(indices)

Upvotes: 3

Related Questions