0

我写了这段代码:

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

谢谢

4

2 回答 2

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)) ));
于 2012-06-02T05:24:17.573 回答
1
currentVector =  ceil(log10(abs(A)));
currentVector(A == 0) = 0;

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

于 2012-06-03T15:26:59.497 回答