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条件不断提醒我C和Java.
谢谢
%# 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)