0

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.

  • `x = ([],1)` doesn’t look like proper MATLAB syntax. Other than that, I don’t see the problem. Why do you think your code is not correct? – Cris Luengo Aug 09 '18 at 15:53
  • Yes this is a pseudo syntax, i don't now how to implement it correct. In the moment i get errors. The main question is, how I have to define the property, that I can fill it in the for-loop. – Prof. Putzmichel Aug 09 '18 at 16:01

1 Answers1

0

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
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Thank your very much, I solve the problem now. It was an mistake in the sub function and in the property declaration, now all works fine. – Prof. Putzmichel Aug 09 '18 at 16:47