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
Star Strider 2015년 5월 25일
편집: Star Strider 2015년 5월 25일

0 개 추천

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
Heather Smith 2015년 5월 25일
Thanks, it worked perfectly! Unfortunately, having another problem now. The numbers (1:10) in this case actually correspond to variable names A,B,C,D,E... I need the program to output the answer in variables- like C,D,E...,A,B I thought it would be simple enough to work out then realized I had no idea how to do it?
Stephen23
Stephen23 2015년 5월 25일
편집: Stephen23 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:
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.

댓글을 달려면 로그인하십시오.

카테고리

태그

질문:

2015년 5월 25일

편집:

2015년 5월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by