Eghbal
Eghbal

Reputation: 3803

Object array implemenation in MATLAB OOP

Suppose that we have this class in MATLAB R2014b :

classdef Pre

properties
    Value
end

methods
    function obj = Pre(F)

        if nargin ~= 0
            m = size(F,1);
            n = size(F,2);
            obj(m,n) = Pre;

            for i = 1:m
                for j = 1:n
                    obj(i,j).Value = F(i,j);
                end
            end
        end
    end
end
end

1) If we erase if nargin~=0 from this code we have this error :

Error using Pre (line 13)
Not enough input arguments.

Error in Pre (line 15)
                obj(m,n) = Pre;

Why? I think this is only checking for number of input arguments !

2) what is obj(m,n) = Pre;? what this line is doing in this code? This is for pre-allocating but how this line can do that?

I checked this class with this syntax: az = Pre([2 3 5;5 3 0])

Upvotes: 1

Views: 65

Answers (1)

hbaderts
hbaderts

Reputation: 14371

1) In the line obj(m,n) = Pre; you call Pre without any input argument, so the variable F doesn't exist in that function call. It would therefore fail to do size(F,1) etc. MATLAB prevents this by throwing the error not enough input arguments. As long as you want the possibility to call Pre with or without input arguments, you need to check if an argument exists or not.

2) This does a pre-allocation. By creating an empty Pre at the location (m,n) of obj, MATLAB will initialize obj as matrix of type Pre and size mxn. (You can verify this for normal variables by typing a(2,2) = 0 in the MATLAB console - it will return a 2-by-2 matrix of zeros).

Upvotes: 1

Related Questions