用"if/else"写一个for/while循环.以更优雅的方式? [英] Write a for/while loop with "if/else" in a more elegant way?

查看:207
本文介绍了用"if/else"写一个for/while循环.以更优雅的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了以下代码:

I've written this code :

AnXm矩阵

[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"的方式编写以上代码?

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

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

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;

那些if/else条件使我想起CJava.

谢谢

推荐答案

%# 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)) ));

这篇关于用"if/else"写一个for/while循环.以更优雅的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆