在算术运算中使用逻辑数组而不是整数数组和值是否有任何缺点? [英] Are there any drawbacks using logical instead of integer arrays and values in arithmetic operations?

查看:70
本文介绍了在算术运算中使用逻辑数组而不是整数数组和值是否有任何缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于涉及整数的运算,逻辑值的向量是否等于采用适当值为0和1的整数的向量?

For operations involving integers, is a vector of logical values equivalent to a vector of integers taking appropriate values of 0 and 1?

如果我在逻辑对象而不是整数对象上进行计算或将函数应用于逻辑对象,会不会遇到意想不到的后果?

Will I run into unexpected consequences if I make computations on or apply functions to logical objects instead of integer objects?

推荐答案

这确实取决于大小写,但是在编程中一如既往:变量的显式转换比隐式的转换好!

It really depends on the case, but as always in programming: the explicit conversion of variables is better than implicitly!

这是一个简单的示例,您可以在其中看到区别:

Here a simple example, where you could see a difference:

x = [0 1 0 1 0]      %// 0     1     0     1     0
y = logical(x)       %// 0     1     0     1     0

y(y) = 5             %// 0     1     0     1     0
x(y) = 5             %// 0     5     0     5     0
y(x) = 5             %// error
x(x) = 5             %// error

因此,要对索引进行索引时,赋值左侧的索引变量将确定输出的类型. 只要您可以确保输出始终为两倍,就不会遇到问题.

So when it comes to indexing the indexed variable on the left hand side of the assignment determines the type of the output. So as long as you can ensure, that your output is always double, you shouldn't run into problems.

看看这个更复杂的例子:

Have a look at this more complex example:

z = double([0 0 0 0 0])
z(y) = x(y) + y(y)

第一个求和是 double ,第二个是逻辑.但是由于它们都是算术运算的一部分,所以两个加法运算符都被视为 double .由于z也是 double ,因此结果也是 double .

the first summand is double, the second is logical. But as they are part of an arithmetic operation both summands are treated double. As z is double as well, the result is double.

z =

     0     2     0     2     0


现在考虑以下几点:


Now consider the following:

z = logical([0 0 0 0 0])
z(y) = x(y) + y(y)  

再次是 double ,第二个是逻辑.再次将它们视为 double .但是z逻辑,因此实际的 double 结果将转换为逻辑.

again the first summand is double, the second is logical. And again they are treated double. But z is logical, so the actually double result is converted to logical.

z =

     0     1     0     1     0

这篇关于在算术运算中使用逻辑数组而不是整数数组和值是否有任何缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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