필터 지우기
필터 지우기

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

조회 수: 5 (최근 30일)
John Allen
John Allen 2023년 5월 8일
답변: Srivardhan 2023년 6월 5일
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