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

JAN*_*JAN 0 matlab for-loop if-statement vectorization

我写了这段代码:

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
Run Code Online (Sandbox Code Playgroud)

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

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

int a = 0;
int b = 10;
a = b > 100 ? b : a;
Run Code Online (Sandbox Code Playgroud)

那些if/else条件不断提醒我CJava.

谢谢

Amr*_*mro 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)) ));
Run Code Online (Sandbox Code Playgroud)

  • @kay:完成了.随意添加对MATLAB文档中相关部分的引用(我确信有很多讨论编写矢量化代码,并执行矩阵索引) (2认同)