Matlab modulo specific behaviour

前端 未结 2 994
既然无缘
既然无缘 2020-12-21 02:05

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

相关标签:
2条回答
  • 2020-12-21 02:22

    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
    
    0 讨论(0)
  • 2020-12-21 02:33

    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
    
    0 讨论(0)
提交回复
热议问题