8 views (last 30 days)

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?

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

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.

Opportunities for recent engineering grads.

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

Start Hunting!
## 0 Comments

Sign in to comment.