Write a for/while loop with “if/else” in a more el

2019-08-18 19:54发布

问题:

I've written this code :

A is a nXm matrix

[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

How can I write the above code in a more "matlab" way ?

Are there any shortcuts for if/else and for loops ? for example in C :

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

Those if/else conditions keeps reminding me of C and Java .

Thanks

回答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)) ));


回答2:

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

Note: in Matlab it is totally legal to apply log on zeros - the result is: -inf.