Search code examples
arraysfunctionmatlabmatlab-deployment

Matlab: Index exceeds matrix dimensions


I am trying to run the following code:

classdef HelloWorld
    properties
        var;
        array;
    end

    methods
        function h = HelloWorld()
            h.var = 30;
            setArray(h);
            disp(h.array(10));
        end

        function setArray(h)
            for i=1:h.var
                h.array(i) = i*2;
            end
        end
    end
end

However, I get the following error:

Index exceeds matrix dimensions.

Error in HelloWorld (line 14)
        disp(h.array(10));

Solution

  • Because you're accessing an empty array.

    What you need is a new copy of HelloWorld which have an initialized array.

    classdef HelloWorld
        properties
            var;
            array;
        end
    
        methods
            function h = HelloWorld()
                h.var = 30;
                h=setArray(h);
                disp(h.array(10));
            end
    
            function h=setArray(h)
                for i=1:h.var
                    h.array(i) = i*2;
                end
            end
        end
    end