2

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?

2 Answers 2

3

Like this : ( using sub2ind )

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

Then,

result = data(indices)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I am wondering if there is any more direct way without converting the indeces.
1

I also find a indirect way without using.

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

1 Comment

That should be column_index*size(data,1) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.