if 语句语法 Matlab

if statement syntax Matlab

我正在尝试将一些 Matlab 代码翻译成 Python。不幸的是我没有 Matlab,所以我无法尝试语法。

我对下面的 if 语句感到困惑

for i = 1:200
    if mod(i,10) == 0 
        i 
    end

然后for循环继续计算一些依赖于i的值。 if 语句的作用是什么?

我还可以问一下稀疏矩阵和零矩阵的区别吗

A = sparse(n,m)
B = zeros(n,m)

谢谢!

if语句检查i除以10的modulus(除后余数)是否为0。

当它被评估为真时,它将数字 i 打印到命令 window。

documentation for modmod(i,10) returns i 除以 10 后的余数,其中 i 是被除数,10 是除数。 if 语句检查余数是否等于 0

通常单独提出问题会更好,但我会尝试同时解决这两个问题:

1) mod函数执行取模运算,即除法后的余数。 mod(i,10) == 0 如果一个数能被 10 整除则为 1,否则为 0。因此,当数字 i 是 10 的倍数时,将执行 if 语句。

由于没有 else 部分,如果条件不成立,则不会发生任何事情。

通过只写i(不带分号),i的当前值被打印到命令window。因此,示例代码的输出将是 1020、...、200.

2) zeros 命令创建一个 "normal" 矩阵(当然)维度为 n x m 的零点。 MATLAB 还有一个特殊的 sparse memory organization. As sparse matrices consist mostly of zeros, you don't need to fill the memory with all those zeros, but you can save the non-zero values and where they are. This is automatically done using the sparse function. To convert a sparse matrix to the "normal" format, you can use the full 函数。

天真的 Python 翻译应该是

for i in range(1, 201):
    if not i % 10:
        print(i)

但我们可以通过指定步长值来节省一些工作,

for i in range(10, 201, 10):
    print(i)