【问题标题】:How to redefine the .^ operator in MATLAB?如何在 MATLAB 中重新定义 .^ 运算符?
【发布时间】:2011-11-26 12:39:58
【问题描述】:

如何在 MATLAB 中重新定义指数函数.^?来自:

x.^y

到:

sign(x).*abs(x.^y))

【问题讨论】:

标签: matlab function operator-overloading exponential redefine


【解决方案1】:

你能在 MATLAB 中重新定义算术运算符吗?...是的

是否应该在 MATLAB 中重新定义算术运算符?...嗯,可能不会。

为什么?因为 MATLAB 中的所有其他函数都希望算术运算符的行为与内置实现所定义的一样。

我已经回答了一些其他有关重载算术运算符和隐藏内置行为的相关问题,我绝对建议您先阅读这些问题,以了解这种方法所涉及的细节、困难和陷阱:

现在我已经完成了我的免责声明,我会把枪交给你,用它可能会朝自己的脚开枪……;)


MATLAB 中的算术运算符具有功能等效项,当您调用它们时会在后台调用它们,在 here 中列出。数组幂运算符.^ 在调用时会调用内置的power 函数。

现在,将为每个使用它的data type 定义一个单独的power 函数。这个函数会放在一个@type目录下,你可以通过which函数查看存在的不同power函数来查看:

>> which power -all
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@single\power)  % single method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@double\power)  % double method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@char\power)    % char method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@int64\power)   % int64 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@int32\power)   % int32 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@int16\power)   % int16 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@int8\power)    % int8 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@uint64\power)  % uint64 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@uint32\power)  % uint32 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@uint16\power)  % uint16 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@uint8\power)   % uint8 method

如果您的变量 xy 将是 double 类型(因为它们在 MATLAB 中是默认的),那么您将不得不隐藏内置的 @double\power 函数。为此,您可以创建一个目录(我们称之为temp),在该目录中创建一个名为@double 的子目录,然后将以下自定义power 函数放在该子目录中:

function result = power(x, y)
  result = sign(x).*abs(builtin('power', x, y));
end

现在,基于function precedence order MATLAB如下,如果你将目录temp添加到MATLAB path,或者如果你只是将current working directory更改为temp,那么上面自定义的power函数当对双变量使用.^ 运算符时,将调用而不是内置的。

【讨论】:

    【解决方案2】:

    不要。它不会是正确的。 (-1).^(1/2) 应该总是给你虚数单位 (i)。您拥有的表达式会给您 (-1).^(1/2) -> -1。更糟糕的是,考虑 (-1)^2。

    创建一个单独的函数来执行您描述的操作。类似的东西

    function a = myPowerFunc(x, y)
    
    a = sign(x).*abs(x.^y);
    

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多