matlabmatlab-class

Matlab class dynamic filling of a property


I'm trying to dynamically fill a property in a Matlab class. I pass vectors to a method function and then compute various parameters. I would like to fill the properties in a for loop, see code example. The OwnClassFunction is just an example of a further function in the class, but is not implemented in the code example. How can I do this correctly?

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

If i try something like that

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

I get the error message Subscripted assignment dimension mismatch.


Solution

  • I don’t have MATLAB in hand to test, but the following should work.

    Your code is pretty close to a correctly functioning method. Change it as follows:

    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