登录论坛

查看完整版本 : 使用isreal的结果不一致


poster
2019-12-10, 20:48
举一个简单的例子:

a = [1 2i]; x = zeros(1,length(a)); for n=1:length(a) x(n) = isreal(a(n)); end 为了使代码矢量化,我尝试了:

y = arrayfun(@isreal,a); 但是结果不一样:

x = 1 0 y = 0 0 我究竟做错了什么?



回答:

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

>> y = arrayfun(@(x) isreal(x(1)),a) ans = 1 0 为什么这样做?我不能完全肯定,但现在看来,当你调用之前对变量执行的索引操作伊斯雷尔 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/isreal.html)如果虚分量为零它会从数组元素中的“复杂”属性。在命令窗口中尝试以下操作:

>> 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 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/arrayfun.html)必须在内部维护传递给ISREAL (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/isreal.html)的数组元素的“ complex”属性,因此即使虚数为零,也将它们全部视为复数。



更多&回答... (https://stackoverflow.com/questions/3602587)