Finding some numbers in a matrix based on their rows and columns numbers without loop application

1 view (last 30 days)
Hi, I have a big matrix, lets say A(1375*3600), and another matrix B(600*2), the two numbers of each row in matrix B refer to the location of a cell in matrix A. For example assume that the first row of B is [150 200] and A(150,200)=300; I can use a 'for loop' to find all the 600 elements of matrix A based on matrix B, but I want to know is there any other approach to solve this problem without loop which is too slow? I tried A(B(:,1),B(:,2)); but it did not work.

Accepted Answer

Walter Roberson
Walter Roberson on 3 Dec 2015
idx = sub2ind( size(A), B(:,1), B(:,2) );
A(idx)
More efficient (but not as clear) is
idx = (B(:,2)-1)*size(A,1) + B(:,1);
A(idx)

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!