필터 지우기
필터 지우기

find value of matrix by position

조회 수: 1 (최근 30일)
Tiki Tiki
Tiki Tiki 2018년 7월 21일
편집: Tiki Tiki 2019년 5월 29일
Hi everyone
Can you help me to optimize code?
this is my code:
aa =
1 4 5 7
9 2 3 8
bb =
1 3
2 4
I want to get value of each row aa by position of row bb. Like this
cc = [1 5; 2 8]
Thank

채택된 답변

Jan
Jan 2018년 7월 21일
편집: Jan 2018년 7월 21일
I guess, that the elements of bb are the row indices related to aa, and the column index is the corresponding column of bb:
aa = [1 4 5 7; ...
9 2 3 8; ...
13 21 33 44];
bb = [1 3; ...
2 4; ...
2 3];
s = size(bb);
c = aa(sub2ind(size(aa), repmat((1:s(1)).', 1, s(2)), bb))
Or faster with a direct call, but without exhaustive error checking:
sa = size(aa, 1);
sb = size(bb, 1);
index = (1:sb).' + (bb - 1) .* sa;
aa(index)
  댓글 수: 5
Jan
Jan 2019년 5월 28일
I've learned it by using sub2ind at first, and then reading the code of sub2ind.m. I've removed all parts for the error checking and simplified the code such that it works for 2 dimensions only. During implementing this as code, I understood the underlying logic: With linear indexing, the formula is almost trivial. :-)
Tiki Tiki
Tiki Tiki 2019년 5월 29일
편집: Tiki Tiki 2019년 5월 29일
Thank
But I find many code of sub2ind.m
How can i know which one? If I try to learn another function like function repmat as you mentioned above.
Have a nice day.
God blesses you.

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

추가 답변 (0개)

카테고리

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