Clear Filters
Clear Filters

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

6 views (last 30 days)
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?

Answers (1)

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);
list = A(lin_idx);
For further reference, please check the following link to know more about “sub2ind” function.
I hope this resolves the issue you were facing.

Community Treasure Hunt

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

Start Hunting!