MATLAB:是否可以在本机结构(单元,结构等)上重载运算符? [英] MATLAB: Is it possible to overload operators on native constructs (cells, structs, etc)?

查看:94
本文介绍了MATLAB:是否可以在本机结构(单元,结构等)上重载运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用单元格来管理我正在处理的某些内容中的数据.我希望能够执行以下操作:

I'm using cells to manage data in some stuff I'm working on. I'd like to be able to do things like:

A = cellfun( @(X)( randn( 5,5 ) ), cell( 5,1 ), 'UniformOutput', 0 );
B = cellfun( @(X)( randn( 5,5 ) ), cell( 5,1 ), 'UniformOutput', 0 );
%#
%# Each of the following would fail if cell member dimensions
%# don't match up
%#
%# matrix sums for each cell entry
%# C = A + B;
C = cellfun( @(X,Y)( X + Y ), A, B, 'UniformOutput', 0 );
%#
%# direct/hadamard product
%# D = A .* B;
D = cellfun( @(X,Y)( X .* Y ), A, B, 'UniformOutput', 0 );
%#
%# matrix-matrix products (not across all entries)
%# E = A * B;
E = cellfun( @(X,Y)( X * Y ), A, B, 'UniformOutput', 0 );

但是,我不希望语​​法过于冗长.当我要做的只是为单元格上的数学运算符提供定义时,为此创建一个新类似乎有点过头了.

However, I don't want the extremely verbose syntax to do it. It seems a bit overboard to create a new class for this when all I want to do is provide a definition for math operators on cells.

问题:上课是唯一的途径吗?

The question: Is a class the only way to go about it?

如果我编写一个类来做到这一点,那无疑会使编写代码更加容易.我看到的最大的负面因素与优化有关,尽管还有其他一些问题困扰我..

If I write a class to do this, it certainly makes it easier to write the code. The biggest negatives I see are related to optimizations, though there's a few other things that bug me about it..

幕后进行的任何优化(例如,当Jacket编译要在GPU上运行的东西时)都可能很难确定要进行的优化.举例来说,假设我有两个单元格(A,B),其中包含许多适当维数的矩阵.如果我编写代码以生成新的单元格:

Any optimizations going on behind the scenes (eg, when Jacket compiles something to run on a GPU) would potentially have a harder time determining what optimizations to make. As an example, suppose I have two cells (A,B) containing a number of matrices of appropriate dimension. If I write code to produce a new cell:

Z = c1*A + c2*B

...使用标量{c1,c2},我可以这样编写它,使Jacket(或其他任何东西)可以轻松确定它应该进行如下计算:

... with scalars {c1,c2}, I can write it in such a way that Jacket (or whatever) will easily determine that it should do the calculations as:

Z{kk} = c1*A{kk} + c2*B{kk}

,或者比这更好的优化.否则.最终可能会导致速度变慢和/或内存效率降低,例如:

or perhaps an even better optimization than that. Otherwise. it may end up with something slower and/or less memory efficient, eg:

temp1 = cellfun( @(X)( c1*X ), A );
temp2 = cellfun( @(X)( c2*X ), B );
Z     = cellfun( @plus, temp1, temp2 );

假设MATLAB或Jacket无法对其进行优化,则最终将占用过多的内存.

Assuming MATLAB or Jacket are unable to optimize it, this would end up using too much memory.

推荐答案

实际上,可以为MATLAB中的内置数据类型创建新的运算符或重载现有的运算符.我在我的答案中描述了一个这样的示例,它回答了另一个有关

It is in fact possible to create new operators or overload existing ones for built-in data types in MATLAB. I describe one example of this in my answer to another SO question about modifying the default overflow behavior of integer types.

首先,您可能需要查看单元格数组当前存在的方法.您可以使用方法来完成此操作,这就是我所得到的在MATLAB R2010b中:

First, you may want to look at what methods currently exist for cell arrays. You can do this using the function METHODS, and here's what I get in MATLAB R2010b:

>> methods cell

Methods for class cell:

aa2nt            issorted         regexptranslate  strfind          
accumarray       newdepfun        reshape          strjust          
cell2struct      nt2aa            rna2dna          strmatch         
ctranspose       nwalign          seq2regexp       strtok           
display          permute          setdiff          transpose        
dna2rna          regexp           setxor           union            
intersect        regexpi          sort             unique           
ismember         regexprep        strcat           

算术运算符方法将在它们的函数等效项中显示,例如plus用于+运算符,或者times用于.*运算符.对于单元阵列,仅定义了transpose方法(.'运算符).您必须自己创建其余部分,定义给定的运算符对单元格数组参数的行为.

The arithmetic operator methods would show up in the above list as their function equivalents, like plus for the + operator or times for the .* operator. Only the transpose method (.' operator) is defined for cell arrays. You would have to create the rest yourself, defining how a given operator will behave for cell arrays arguments.

您可以先创建一个名为@cell的新文件夹,然后将其放在

You can do this by first making a new folder called @cell and placing it in an existing folder on your MATLAB path. You would then place your new methods in the @cell folder. For example, a very simple implementation of a plus method for cell arrays (without any input-checking, error-checking, etc.) would be this:

function C = plus(A,B)
  C = cellfun(@plus,A,B,'UniformOutput',false);  %# Apply plus cell-wise
end

在上面的代码中,您可能首先要检查操作数AB是相同大小的单元格数组.但是,您可以创建所需的任何独特功能,例如允许将B作为标量值,并将其添加到A的每个单元格中.完全由您来定义+运算符对单元格数组的行为.

In the above code, you would probably first want to check that the operands A and B are cell arrays of the same size. However, you could create whatever unique functionality you want, such as allowing B to be a scalar value which would get added to every cell of A. It's totally up to you to define how the + operator will behave for cell arrays.

这将允许您以更加紧凑的方式编写代码,如本例所示:

This would then allow you to write your code in a much more compact way, as in this example:

>> A = {[1 2 3] [4 5] 6};  %# One 3-element cell array
>> B = {5 [4 5] 2};        %# Another 3-element cell array
>> C = A+B;                %# Use the new plus operator
>> C{:}                    %# Display the cell contents

ans =

     6     7     8

ans =

     8    10

ans =

     8

我不能真正谈论幕后的优化及其对它们的影响.我知道文档提高性能的技术" 是专门针对提到有关重载内置函数 :

I can't really speak to the behind-the-scenes optimizations and how this might affect them. I know that the documentation "Techniques for Improving Performance" specifically mentions this about overloading built-in functions:

重载MATLAB内置函数 在任何标准MATLAB数据上 班级会产生负面影响 表现.例如,如果您 重载plus函数来处理 任何整数类 不同的是,您可能会阻碍 MATLAB内置的优化 plus的功能代码,因此可能 放慢所有可用程序

Overloading MATLAB built-in functions on any of the standard MATLAB data classes can negatively affect performance. For example, if you overload the plus function to handle any of the integer classes differently, you may hinder certain optimizations in the MATLAB built-in function code for plus, and thus may slow down any programs that make use of this overload.

但是,在您的情况下,您不会为类重载现有的函数.您只是在创建该类中不存在的新类,因此很难说这可能最终对性能产生什么影响.

However, in your case you aren't overloading existing functions for a class. You're simply creating new ones that didn't exist for that class, so it's hard to say what effect this may ultimately have on performance.

这篇关于MATLAB:是否可以在本机结构(单元,结构等)上重载运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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