使用伊斯雷尔不一致的结果 [英] inconsistent results using isreal

查看:169
本文介绍了使用伊斯雷尔不一致的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拿这个简单的例子:

a = [1 2i];

x = zeros(1,length(a));
for n=1:length(a)
    x(n) = isreal(a(n));
end

在试图矢量化code,我想:

In an attempt to vectorize the code, I tried:

y = arrayfun(@isreal,a);

但结果是不相同的:

But the results are not the same:

x =
     1     0
y =
     0     0

我在做什么错了?

What am I doing wrong?

推荐答案

这肯定似乎是一个错误,但这里有一个解决方法:

This certainly appears to be a bug, but here's a workaround:

>> y = arrayfun(@(x) isreal(x(1)),a)

ans =

     1     0

为什么这项工作?我不的完全的肯定,但现在看来,当你对变量执行的索引操作的的调用的ISREAL 的,如果虚部为零,它会从数组元素的复杂属性。试试这个在命令窗口:

Why does this work? I'm not totally sure, but it appears that when you perform an indexing operation on the variable before calling ISREAL it removes the "complex" attribute from the array element if the imaginary component is zero. Try this in the Command Window:

>> a = [1 2i];         %# A complex array
>> b = a(1);           %# Indexing element 1 removes the complex attribute...
>> c = complex(a(1));  %# ...but we can put that attribute back
>> whos
  Name       Size            Bytes  Class      Attributes

  a          1x2                32  double     complex   
  b          1x1                 8  double                  %# Not complex
  c          1x1                16  double     complex      %# Still complex

显然, ARRAYFUN 必须在内部保持的的复杂属性数组元素把它传递给伊斯雷尔,从而把它们全当成甚至是复数如果虚分量是零。

Apparently, ARRAYFUN must internally maintain the "complex" attribute of the array elements it passes to ISREAL, thus treating them all as being complex numbers even if the imaginary component is zero.

这篇关于使用伊斯雷尔不一致的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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