# Finding values in a matrix using a vector of varying column position.

4 views (last 30 days)
John Allen on 8 May 2023
Answered: Srivardhan on 5 Jun 2023
Let's say I have a 3x3 matrix (A) and list of column indexes such as [2,3,2] (C). At each row of the matrix, I want to grab a value at a certain column index. I know if I could make a for loop where I grab the value I want in A like so : list = A(i, C(i)). The problem is the matrix I am working with is very large and setting up a for loop like this time consuming. I thought I could index my column list directly into A like so, list = A(:, C), to get the associated values at each row with each desired column position but this does not work.
Any suggestions?

Srivardhan on 5 Jun 2023
Hi John,
As per my understanding, you would like to find value in each row of the matrix using a vector of varying column position efficiently.
One of the approach would be using “for” loop. We can also solve this problem using “sub2ind” function, which returns the linear indices corresponding to the row and column vector of the matrix.
Here is the code you can check:
A = [1 2 3; 4 5 6; 7 8 9];
C = [2 3 2];
lin_idx = sub2ind(size(A), 1:size(A,1), C);
disp(lin_idx);
list = A(lin_idx);
disp(list);
I hope this resolves the issue you were facing.