フィルターのクリア

How do I make a vector into a loop?

1 回表示 (過去 30 日間)
Laura
Laura 2013 年 2 月 6 日
for example I need to make the last element (N) in my vector such that (N+1) will correspond to the first element in the vector?
  1 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 6 日
Can you give a short example: if x=[1 2 3 4], what should be the result?

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

採用された回答

Dan K
Dan K 2013 年 2 月 6 日
編集済み: Dan K 2013 年 2 月 6 日
I think I understand... Are you saying that if you have a five element vector A(1:5), then you want A(6) to actually reference A(1)?
One way I can see to do this is to create a custom index function as an anonymous function. This is a way of doing it for reading only.
>> A = 1:5
A =
1 2 3 4 5
>> B = @(A,ind)A(mod(ind,length(A)))
B =
@(A,ind)A(mod(ind,length(A)))
>> B(A,2)
ans =
2
>> B(A,7)
ans =
2
>> B(A,8)
ans =
3
Here's a quick way of doing it for writing:
>> A = 1:5;
>> realind = @(x)mod(x,length(A));
>> A(realind(27))
ans =
2
>> A(realind(27)) = 5
A =
1 5 3 4 5
>>
  2 件のコメント
Matt Tearle
Matt Tearle 2013 年 2 月 6 日
Nice! Slight glitch, though: B(A,5) will barf. You need to tweak the mod calculation:
>> B = @(A,ind)A(1+mod(ind-1,length(A)))
Laura
Laura 2013 年 2 月 7 日
Thanks this is what i meant and ive managed to do it now. Thanks again.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by