【问题标题】:Write a for/while loop with "if/else" in a more elegant way?用“if/else”以更优雅的方式编写一个 for/while 循环?
【发布时间】:2012-06-07 06:25:57
【问题描述】:

我已经写了这段代码:

A 是一个nXm 矩阵

[nA, mA] = size(A);

currentVector(nA,mA) = 0;
for i = 1: nA
    for j = 1 : mA
        if A (i,j) ~= 0
            currentVector(i,j) = ceil(log10( abs(A(i,j)) ));
        else
            currentVector(i,j) = 0;
        end
    end
end

如何以更“matlab”的方式编写上述代码?

是否有 if/else 和 for 循环的快捷方式?例如在C

int a = 0;
int b = 10;
a = b > 100 ? b : a;

那些if/else 条件不断让我想起CJava

谢谢

【问题讨论】:

    标签: matlab if-statement for-loop vectorization


    【解决方案1】:
    %# initialize a matrix of zeros of same size as A
    currentVector = zeros(size(A));
    
    %# find linear-indices of elements where A is non-zero
    idx = (A ~= 0);
    
    %# fill output matrix at those locations with the corresponding elements from A
    %# (we apply a formula "ceil(log10(abs(.)))" to those elements then store them)
    currentVector(idx) = ceil(log10( abs(A(idx)) ));
    

    【讨论】:

    • 最好的解决方案,但我想你应该做一些解释。 ;-)
    • @kay:完成。随意添加对 MATLAB 文档中相关部分的引用(我相信有很多讨论编写矢量化代码和执行矩阵索引)
    • @Amro:太棒了,我会从现在开始使用它。谢谢!
    【解决方案2】:
    currentVector =  ceil(log10(abs(A)));
    currentVector(A == 0) = 0;
    

    注意:在 Matlab 中应用对零的登录是完全合法的 - 结果是:-inf。

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 1970-01-01
      • 2021-11-23
      • 2023-01-21
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多