我写了这段代码:
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
条件不断提醒我C
和Java
。
谢谢
答案 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。