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

22 vues (au cours des 30 derniers jours)
Rowan Lawrence
Rowan Lawrence le 11 Déc 2019
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?

Réponses (4)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH le 11 Déc 2019
n=3;
k=[n 1:n-1];
answer=k(mod(1:15,n)+1)

per isakson
per isakson le 11 Déc 2019
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 le 11 Déc 2019
startVector = 1:15;
vec = mod(startVector - 1, 3) + 1;

Image Analyst
Image Analyst le 11 Déc 2019
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.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by