Matlab模数特定行为 [英] Matlab modulo specific behaviour

查看:61
本文介绍了Matlab模数特定行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.假设我有四个可能的值{1 2 3 4},我想要mod函数的特定行为

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

我寻求的行为就是这个

 1 mod 4 = 1
 2 mod 4 = 2
 3 mod 4 = 3
 4 mod 4 = 4

但是我在matlab上得到了以下结果.

but I have the following results with matlab.

 1 mod 4 = 1
 2 mod 4 = 2
 3 mod 4 = 3
 4 mod 4 = 0

是否有关于如何在MATLAB中以最简单的方式实现所需行为的想法?

Are there any ideas as how to achieve the desired behavior with the simplest way possible in MATLAB?

推荐答案

怎么样:

function [result] = my_mod(x,y)
m = mod(x,y);
result = m+~m*y;

~取反mod的结果,即:

  • ~0 == 1
  • ~1 == 0
  • ~2 == 0
  • ...
  • ~0 == 1
  • ~1 == 0
  • ~2 == 0
  • ...

因此,仅当mod的结果为0时,才添加y.

So we only add y if the result from mod is 0.

演示

>> my_mod(1:8, 4)

ans =

 1     2     3     4     1     2     3     4

这篇关于Matlab模数特定行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆