Using the Mod Function to Turn a Vector (i.e. 1:15) into [1, 2, 3, 1, 2, 3, 1, 2, 3] etc.
31 views (last 30 days)
Show older comments
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?
0 Comments
Answers (4)
per isakson
on 11 Dec 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
0 Comments
Image Analyst
on 11 Dec 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.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!