Filter löschen
Filter löschen

How to avoid for loop when indexing?

1 Ansicht (letzte 30 Tage)
Mantas Vaitonis
Mantas Vaitonis am 2 Jul. 2018
Kommentiert: Mantas Vaitonis am 2 Jul. 2018
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 Kommentare
Stephen23
Stephen23 am 2 Jul. 2018
@Mantas Vaitonis: given that pairs contains non-integer values, what do you expect
pairs(i,pairs(i,:));
to do?
Mantas Vaitonis
Mantas Vaitonis am 2 Jul. 2018
Those values suppose to be integer, i fixed my commnet, and should return valuse by index stored in pairs.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 2 Jul. 2018
Bearbeitet: Jan am 2 Jul. 2018
s = size(pairs);
index = sub2ind(s, repmat((1:s(1)).', 1, s(2)), pairs)
cc = pairs(index)
  3 Kommentare
Jan
Jan am 2 Jul. 2018
Bearbeitet: Jan am 2 Jul. 2018
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 am 2 Jul. 2018
Maybe I did mistake when copying your code, now it did work, thank you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by