필터 지우기
필터 지우기

Is it possible to extract the values with a vector of indices for each row without using the for statement from the matrix?

조회 수: 3 (최근 30일)
Consider the following example.
A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]; % reference matrix
b = [2; 1; 1; 3]; % index for each row that I want to extract
for i=1:size(A,1)
y(i,1) = A(i,b);
end
I am using the above code to extract values that I want.
Is there any simple function to implement the above script fast?

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 6월 17일
편집: Ameer Hamza 2020년 6월 17일
see sub2ind()
A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]; % reference matrix
b = [2; 1; 1; 3]; % index for each row that I want to extract
idx = sub2ind(size(A), 1:size(A,1), b.');
A(idx)
Result
>> A(idx)
ans =
2 4 7 12

추가 답변 (1개)

KSSV
KSSV 2020년 6월 17일
편집: KSSV 2020년 6월 17일
May be you are looking for
A(b,:)
The other
A(:,b)
will work, but in your case b has number 4 and in A there are only 3 columns.
To extract a complete row or column, : can be use
A(1,:) % picks the 1st row and all columns
A(:,3) % picks the allrows and third column
A(2,3) % pciks the second row and third column
  댓글 수: 1
Danny
Danny 2020년 6월 17일
That is my typo, so I correct it.
However, I've already done above, but this is not working in my the latest version of Matlab.
>> piset
piset =
9 10 6 7 8 4 5 3 2 1
7 8 5 10 6 4 9 3 2 1
9 10 8 6 7 4 3 5 2 1
7 9 8 6 5 10 3 4 2 1
7 6 9 10 5 8 3 4 2 1
7 10 9 4 5 6 8 2 3 1
10 5 9 6 7 4 8 2 3 1
10 9 8 7 4 5 6 3 2 1
8 10 6 9 7 5 4 2 3 1
9 7 10 6 4 5 8 1 2 3
8 5 9 7 4 10 3 6 2 1
7 9 6 10 8 3 4 5 2 1
6 8 10 7 9 4 5 3 2 1
7 8 6 3 2 10 9 5 4 1
9 5 7 6 10 8 2 3 4 1
>> lset
lset =
8
7
7
2
3
3
9
2
4
10
3
6
5
7
1
>> piset(:,lset)
ans =
3 5 5 10 6 6 2 10 7 1 6 4 8 5 9
3 9 9 8 5 5 2 8 10 1 5 4 6 9 7
5 3 3 10 8 8 2 10 6 1 8 4 7 3 9
4 3 3 9 8 8 2 9 6 1 8 10 5 3 7
4 3 3 6 9 9 2 6 10 1 9 8 5 3 7
2 8 8 10 9 9 3 10 4 1 9 6 5 8 7
2 8 8 5 9 9 3 5 6 1 9 4 7 8 10
3 6 6 9 8 8 2 9 7 1 8 5 4 6 10
2 4 4 10 6 6 3 10 9 1 6 5 7 4 8
1 8 8 7 10 10 2 7 6 3 10 5 4 8 9
6 3 3 5 9 9 2 5 7 1 9 10 4 3 8
5 4 4 9 6 6 2 9 10 1 6 3 8 4 7
3 5 5 8 10 10 2 8 7 1 10 4 9 5 6
5 9 9 8 6 6 4 8 3 1 6 10 2 9 7
3 2 2 5 7 7 4 5 6 1 7 8 10 2 9
>>

댓글을 달려면 로그인하십시오.

카테고리

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