How to cycle through a vector in function?
古いコメントを表示
I've defined a row vector 1:10, then use randi(10). Say from randi(10) I got five; I want the program to output 5, 6, 7, 8, 9, 10, 1, 2, 3, 4. I don't know of any way to do this other than a painfully unelegant, systematic typing each of the possible numbers from the randi function and the output I want. Is there a better way?
回答 (1 件)
Star Strider
2015 年 5 月 25 日
編集済み: Star Strider
2015 年 5 月 25 日
I believe you want circshift:
v = 1:10;
r = randi(10)
vr = circshift(v, [0 1-r])
producing (in one instance):
r =
6
vr =
6 7 8 9 10 1 2 3 4 5
No painful or inelegant typing needed!
(W&L and UVA here!)
3 件のコメント
Heather Smith
2015 年 5 月 25 日
"I thought it would be simple enough.." but it really is not simple at all! Please do not dynamically define and rearrange variable names... there are much better ways to program.
The answer is simple: instead of keeping lots of separate variables, keep them all together in one matrix or perhaps a cell array. Then you can simply use Star Strider's answer as indices to the matrix / cell array and the problem is solved.
Working with variables names dynamically like you are trying to do is generally discouraged, as it is a poor programming practice, for lots of reasons. Read this to know why:
Star Strider
2015 年 5 月 25 日
My pleasure!
Using alphabetic single-character variable names, you can do something like this:
v = strsplit(sprintf('%c ','A':'J'), ' ');
v = v(1:end-1);
r = randi(10)
vr = circshift(v, [0 1-r])
It would be best for these to represent rows or columns in a cell array rather than individual variables, but if you are stuck with legacy code that defines them as individual variables, you can then use the eval function to work with them. However, if at all possible, use eval once to put them into a cell array, then use the array and subscript references to it in the rest of your code.
カテゴリ
ヘルプ センター および File Exchange で Whos についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!