How can I index a vector based on the vector's values?

10 ビュー (過去 30 日間)
Shahriyar Karim
Shahriyar Karim 2020 年 3 月 13 日
コメント済み: Shahriyar Karim 2020 年 3 月 13 日
Say I have a vector,
V = [2 5 4 1 3]
and I want to use the numbers of the vector itself to index. Starting from 1, I go to the first element in V; which = 2.
From there, I want to go to the 2nd element of V--5, then 3, then 4, and finally 1.
How would I go about extracting Vnew = [1 2 4 5 3]?
So far I've tried:
V(V) = [5 3 1 2 4]
I'm assuming it'll require some sort of loop but I'm completely stumped right now.
EDIT: Apologies for the confusion in the explanation above; I don't need the produced vector, but the order in which it's produced--if that makes any sense.
Starting at index 1 of V, I get 2. Then I use 2 as the index of V to get 5--use 5 to get 3--3 for 4---4 loops back to 1.
The part I need is the order in which I loop through. The first index will always be 1, but say the first element of V was 3. I'd then go to the THIRD element of V and Vnew for the third element would equal 2. Using this method, I need to output Vnew = [1 2 4 5 3].
  3 件のコメント
Shahriyar Karim
Shahriyar Karim 2020 年 3 月 13 日
That's an answer I got previously, but it isn't exactly what I'm looking for. I've tried to clarify a bit more in the original post
BobH
BobH 2020 年 3 月 13 日
編集済み: BobH 2020 年 3 月 13 日
V = [2 5 4 1 3]
sequence followed is 1, then 2 5 3 4, then 1
2 5 3 4 1 are found in V in these positions 1 2 5 3 4
You consistently show a 4 in the third position of your desired output, and I can't see how you place a 4 there.

サインインしてコメントする。

採用された回答

BobH
BobH 2020 年 3 月 13 日
編集済み: BobH 2020 年 3 月 13 日
V = [2 5 4 1 3];
R(1) = V(1);
for i = 2:length(V)
R(end+1) = V( R(i-1) );
end
R % new vector
R =
2 5 3 4 1
% The sequence of indices followed within V
S = [1 R(1:length(V)-1)]
S =
1 2 5 3 4
  1 件のコメント
Shahriyar Karim
Shahriyar Karim 2020 年 3 月 13 日
Okay this makes sense. I was overthinking it way too much--that's probably why I was confused over the indexing in your other comment; it makes sense now. Thank you!

サインインしてコメントする。

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2020 年 3 月 13 日
I believe it is like this
V = [2 5 4 1 3];
newV=zeros(size(V));
index=1;
for k=1:numel(V)
newV(k)=V(index)
index=newV(k);
end
  2 件のコメント
Shahriyar Karim
Shahriyar Karim 2020 年 3 月 13 日
This is what I got before in a previous answer; but it isn't exactly what I'm looking for. I've edited the original post for a bit more clarification.
Fangjun Jiang
Fangjun Jiang 2020 年 3 月 13 日
I don't get it. Your expected Vnew is wrong according to your explaination.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by