简体   繁体   中英

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));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM