【问题标题】:Property value doesn't get saved in class variable属性值未保存在类变量中
【发布时间】:2018-11-26 13:13:26
【问题描述】:

我有以下类,其中包含计算信号傅立叶变换的函数。

函数有效,但如果在使用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

【问题讨论】:

    标签: matlab class oop fft


    【解决方案1】:

    首先,你的类函数应该返回 obj 对象:

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

    不返回它与拥有一个不返回任何内容的独立函数相同 - 您没有将结果存储在任何地方!


    那么您可能想了解值和句柄类:

    您的类目前是一个值类。请阅读以下代码中的 cmets 以了解预期行为:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多