Write a for/while loop with “if/else” in a more elegant way?

余生长醉 提交于 2019-12-11 17:44:41

问题


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.



来源:https://stackoverflow.com/questions/10859990/write-a-for-while-loop-with-if-else-in-a-more-elegant-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!