首页 > 解决方案 > Matlab类动态填充一个属性

问题描述

我正在尝试动态填充 Matlab 类中的属性。我将向量传递给方法函数,然后计算各种参数。我想在 for 循环中填充属性,请参见代码示例。OwnClassFunction 只是类中另一个函数的示例,但在代码示例中没有实现。我怎样才能正确地做到这一点?

classdef Sicherung < handle      

    properties
        x = ([],1)
    end

    methods
        function examplefunction(object,...
                single_parameter_vector) % (n,1) n can be any size 

            for i=1:length(param_vector)

                [object.x(i,1)] = object.OwnClassFunction(single_parameter_vector(i,1));
            end
        end
    end
end

如果我尝试这样的事情

...
properties
   x = []
end
...
function ...(object,parameter)
   for i=1:length(parameter)
     [object.x(i)] = function(parameter(i));
   end

我收到错误消息Subscripted assignment dimension mismatch

标签: matlabmatlab-class

解决方案


我手头没有 MATLAB 来测试,但以下应该可以工作。

您的代码非常接近正确运行的方法。更改如下:

classdef Sicherung < handle      

    properties
        x = [] % initialize to empty array
    end

    methods
        function examplefunction(object,param_vector)
            if ~isvector(param_vector)
                 error('vector expected') % check input
            end
            n = numel(param_vector)
            object.x = zeros(n,1); % preallocate
            for i=1:n
                object.x(i) = object.OwnClassFunction(param_vector(i));
            end
        end
    end
end

推荐阅读