Using the Mod Function to Turn a Vector (i.e. 1:15) into [1, 2, 3, 1, 2, 3, 1, 2, 3] etc.

23 ビュー (過去 30 日間)
Rowan Lawrence
Rowan Lawrence 2019 年 12 月 11 日
回答済み: Image Analyst 2019 年 12 月 11 日
I'm currently reading through the book MATLAB for Clinical and Cognitive Scientists by Mike Cohen. In the book, he mentions a 'neat trick' to covert some vector of linearly-spaced numbers (my e.g. 1:15) into a vector of numbers counting up from 1 to N over and over, using the mod function. This is supposed to work for any arbitrary number n (obviously as we leave greater remainder until we reach the number).
For some reason I just cannot implement what he has suggested. All I can think to do is
mod(startVector, 3)
but obviously the remainder of 3 and 3 is 0, so I end up with [1, 2, 0, 1, 2, 0] etc.
It isn't very necessary, I'm just a little confused that he mentioned something so simple like this that I can't fathom a way to implement. Could anyone help me with this simple problem please?

回答 (4 件)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019 年 12 月 11 日
n=3;
k=[n 1:n-1];
answer=k(mod(1:15,n)+1)

per isakson
per isakson 2019 年 12 月 11 日
Or
%%
startVector = 1:15;
vec = mod( startVector, 3 );
vec(vec==0)=3 % replace all zeros by 3
vec =
Columns 1 through 14
1 2 3 1 2 3 1 2 3 1 2 3 1 2
Column 15
3

Walter Roberson
Walter Roberson 2019 年 12 月 11 日
startVector = 1:15;
vec = mod(startVector - 1, 3) + 1;

Image Analyst
Image Analyst 2019 年 12 月 11 日
Yeah, you could do it like that, though a much more straightforward way is to simply use repmat
n = 5; % Whatever you want
out = repmat(1:3, [1, n]) % Replicate [1, 2, 3] five times.
However with the above code, n must be an integer whereas your trick can have a non-integer multiple of n, in case that might be needed.

カテゴリ

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