Using the Mod Function to Turn a Vector (i.e. 1:15) into [1, 2, 3, 1, 2, 3, 1, 2, 3] etc.
31 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(4 个)
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
0 个评论
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!