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

3 次查看(过去 30 天)
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?

回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by