用更优雅的方式用“if / else”写一个for / while循环?

时间:2012-06-02 05:16:48

标签: matlab if-statement for-loop vectorization

我写了这段代码:

AnXm矩阵

[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

谢谢

2 个答案:

答案 0 :(得分:5)

%# 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)) ));

答案 1 :(得分:1)

currentVector =  ceil(log10(abs(A)));
currentVector(A == 0) = 0;

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