How to avoid for loop when indexing?

조회 수: 1 (최근 30일)
Mantas Vaitonis
Mantas Vaitonis 2018년 7월 2일
댓글: Mantas Vaitonis 2018년 7월 2일
Hello,
I have the following for loop, where pairs(500x10), is there to calculate cc without for loop?
for i=1:500
cc(i,:)=pairs(i,pairs(i,:));
end
  댓글 수: 4
Stephen23
Stephen23 2018년 7월 2일
@Mantas Vaitonis: given that pairs contains non-integer values, what do you expect
pairs(i,pairs(i,:));
to do?
Mantas Vaitonis
Mantas Vaitonis 2018년 7월 2일
Those values suppose to be integer, i fixed my commnet, and should return valuse by index stored in pairs.

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

채택된 답변

Jan
Jan 2018년 7월 2일
편집: Jan 2018년 7월 2일
s = size(pairs);
index = sub2ind(s, repmat((1:s(1)).', 1, s(2)), pairs)
cc = pairs(index)
  댓글 수: 3
Jan
Jan 2018년 7월 2일
편집: Jan 2018년 7월 2일
pairs = [5 1 4 5 1];
s = size(pairs);
index = sub2ind(s, repmat((1:s(1)).', 1, s(2)), pairs)
cc = pairs(index)
cc =
1 5 5 1 5
I don't know why you get [4 5 2 4 5]. Please try it again.
Mantas Vaitonis
Mantas Vaitonis 2018년 7월 2일
Maybe I did mistake when copying your code, now it did work, thank 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