属性 值未保存在 class 变量中

Property value doesn't get saved in class variable

我有下面的 class,其中包含用于计算信号傅里叶变换的函数。

函数有效,但如果在使用 dft 方法后尝试调用 obj.x_k,则向量为空。

有人知道为什么吗?

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

首先,您的 class 函数应该 return obj 对象:

function obj = dft( obj )
    % ... same code ...
end

不 return 它与具有不 return 任何东西的独立函数相同 - 您不会将结果存储在任何地方!


那么您可能想了解值并处理 classes:

您的 class 目前是 值 class。请阅读以下代码中的注释以了解预期行为:

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(); 

如果您不想将结果对象重新赋值,您可以使用 句柄 class

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();   

有关更多信息,请阅读文档。