How to avoid for loop when indexing?

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