I have the following problem. Let\'s say I have four possible values {1 2 3 4}
and I want a specific behavior of mod function
The behavior I seek is th
How about:
function [result] = my_mod(x,y)
m = mod(x,y);
result = m+~m*y;
The ~
negates the result from mod
, i.e. :
~0 == 1
~1 == 0
~2 == 0
So we only add y
if the result from mod
is 0
.
demo
>> my_mod(1:8, 4)
ans =
1 2 3 4 1 2 3 4
If A
holds those values, you can subtract 1, perform mod
and add back 1.
Sample run -
>> A = 1:8
A =
1 2 3 4 5 6 7 8
>> mod(A-1,4)+1
ans =
1 2 3 4 1 2 3 4