Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
举一个简单的例子:
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 为什么这样做?我不能完全肯定,但现在看来,当你调用之前对变量执行的索引操作伊斯雷尔如果虚分量为零它会从数组元素中的“复杂”属性。在命令窗口中尝试以下操作: >> 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必须在内部维护传递给ISREAL的数组元素的“ complex”属性,因此即使虚数为零,也将它们全部视为复数。 更多&回答... |
![]() |
![]() |