首页 > 解决方案 > Matlab在构造函数中无法更改类的参数

问题描述

我正在调用一个函数来更改其构造函数中的类的参数,但是,我无法更改这些值。这是一个错误还是故意的?

在下面的示例中,我在构造函数中调用函数“calculateCalculatedProperties()”。“calculateCalculatedProperties()”调用“Velocity()”和“Length()”函数来设置速度和长度属性的新值。但是,构造函数(对象实例)的最终产品属性没有改变。

classdef piping
    %PIPING Summary of this class goes here
    %   Detailed explanation goes here
    
    properties 
        flowRate
        diameter
        startLocation location
        endLocation location
    end

    
    
    methods
        function self = piping(flowRate, diameter, startLocation, endLocation)
            
            self.flowRate = flowRate;
            self.diameter = diameter;
            self.startLocation = startLocation;
            self.endLocation = endLocation;
            
            self.calculateCalculatedProperties();
                       
        end
        
        function self = calculateCalculatedProperties(self)
            fprintf("hey")
            self.Velocity();
            self.Length();
        end
        
        
         function self = Velocity(self)
             self.velocity = self.flowRate / (pi * self.diameter^2 / 4);
         end
        
         function self = Length(self)
            self.length = location.calculateDistance(self.startLocation,self.endLocation) ;
            fprintf("hey this is lengthhhh")
            self.flowRate = 10000000;
         end

        
    end
    
    properties % Calculated properties
        
        velocity
        length
    end
end

标签: matlaboopmatlab-class

解决方案


这里的问题是您使用的是值类,而不是句柄类。请注意,在您的 Velocity 方法中,您将返回“self”的实例,在值类中,这些方法调用返回一个单独的对象,该对象在此代码中被忽略。

话虽如此,有两种可能的解决方案:

  1. 捕获值对象的输出并返回最终的修改对象。

     function self = piping(flowRate, diameter, startLocation, endLocation)
         % ...
         self = self.calculateCalculatedProperties();      
     end
    
     function self = calculateCalculatedProperties(self)
         fprintf("hey")
         self = self.Velocity();
         self = self.Length();
     end
    
  2. 使用句柄类创建一个可变对象。

     classdef piping < handle
         % ...
     end
    

有关详细信息,请参阅句柄和值类的比较。


推荐阅读