我有下面的类,它包含用于计算信号的傅里叶变换的函数。
这些功能有效,但如果在使用obj.x_k
方法后尝试调用dft
,则向量为空。
有人知道为什么吗?
classdef DFT
properties
x_in
len
x_k
ix_k
end
methods
% Konstruktor
function obj = DFT(in_v)
obj.len = length(in_v);
obj.x_in = in_v;
obj.x_k = zeros(1,obj.len);
obj.ix_k = zeros(1,obj.len);
end
%Berechnet diskrete Fourier Transformation eines Signals
function dft(obj)
i=sqrt(-1);
for j=0:obj.len-1
for l=0:obj.len-1
obj.x_k(j+1)=obj.x_k(j+1)+(obj.x_in(l+1)*exp((-i)*2*pi*j*l/obj.len));
end
end
for j = 0:obj.len-1
sprintf('x%d: %f + %fi', j+1,obj.x_k(j+1), obj.x_k(j+1)/1i)
end
obj.x_k
end
%Berechnet inverse diskrete Fourier Transformation eines Signals
function inversedft(obj)
i=sqrt(-1);
for n=0:obj.len-1
for k=0:obj.len-1
obj.ix_k(n+1)=(obj.ix_k(n+1)+(obj.x_in(k+1)*exp(i*2*pi*k*n/obj.len)));
end
end
obj.ix_k = 1/obj.len*obj.ix_k;
for k = 0:obj.len-1
sprintf('ix%d: %f + %fi', k+1,obj.ix_k(k+1), obj.ix_k(k+1)/1i)
end
end
end
end
答案 0 :(得分:2)
首先,您的类函数应返回obj
对象:
function obj = dft( obj )
% ... same code ...
end
不返回它与具有不返回任何内容的独立功能相同 - 您不会将结果存储在任何地方!
然后您可能想了解价值并处理类:
您的课程目前是价值等级。请阅读以下代码中的注释以了解预期的行为:
myDFT = DFT(in_v); % Create DFT object with some input
% Run the method, but don't assign the result to anything! myDFT is unchanged.
% Pointless unless you don't expect the object to be updated.
myDFT.dft();
% Run the method and assign the obj output back to the myDFT object.
% *This is what you should do for a value class*
myDFT = myDFT.dft();
如果您不想重新分配结果对象,可以使用句柄类
classdef DFT < handle
% ... same code ...
end
现在,每次访问myDFT
对象时,您都会在内存中引用相同的对象,而不是之前的某些有价值的实例。请注意区别:
myDFT = DFT(in_v); % Create DFT object with some input
% Run the method, myDFT is updated without assigning back!
% This is because the same instance is changed in memory.
% *This is what you should do for a handle class*
myDFT.dft();
% This now isn't something you want to or need to do...
myDFT = myDFT.dft();
有关更多信息,请阅读文档。