【发布时间】:2014-07-06 18:07:17
【问题描述】:
我在 MATLAB 中有一个表示虚数的类。我有一个构造函数和两个数据成员:real 和 imag。我在一个类中使用重载运算符,我想让它与矩阵一起使用:
function obj = plus(o1, o2)
if (any(size(o1) ~= size(o2)))
error('dimensions must match');
end
[n,m] = size(o1);
obj(n,m) = mycomplex();
for i=1:n
for j=1:m
obj(i,j).real = o1(i,j).real + o2(i,j).real;
obj(i,j).imag = o1(i,j).imag + o2(i,j).imag;
end
end
end
但我不想使用 for 循环。我想做类似的事情:
[obj.real] = [o1.real] + [o2.real]
但我不明白为什么它不起作用......错误说:
“错误 + 输出参数过多”。
我知道在 MATLAB 中最好避免 for 循环以加快速度...有人可以解释一下为什么这不起作用,以及在 MATLAB 中考虑向量化的正确方法以及我的函数示例吗?
提前致谢。
编辑:我的复杂类的定义:
classdef mycomplex < handle & matlab.mixin.CustomDisplay
properties (Access = public)
real;
imag;
end
methods (Access = public)
function this = mycomplex(varargin)
switch (nargin)
case 0
this.real = 0;
this.imag = 0;
case 1
this.real = varargin{1};
this.imag = 0;
case 2
this.real = varargin{1};
this.imag = varargin{2};
otherwise
error('Can''t have more than two arguments');
end
obj = this;
end
end
end
【问题讨论】:
-
您是否有理由不使用对复数的内置支持?
-
不,这只是为了练习。
-
这与常规的 MATLAB 结构非常相似,所以这里有一些相关的问题:Matlab: Assigning same value to field in struct array, Updating one field in every element of a Matlab struct array
标签: matlab oop operator-overloading vectorization matlab-class