Question

I'm attempting to make a crude implementation of the AP CS 'gridworld' using matlab, albiet with fewer classes. So far I have a superclass 'Location' with the properties row and col. Next I have 'Grid' with just a cell array called grid. Using the Grid.get command, I can retrieve objects from that cell array. The problem though, is that I cannot get the Grid.put function to work. Testing without using the function allows me to put test strings into testGrid.grid{}, but the function doesn't seem to work.

classdef Location
properties
    row;
    col;
end
methods
    %constructor, intializes with rows/columns
    function loc = Location(r,c)
        if nargin > 0
            loc.row = r;
            loc.col = c;
        end
    end

    function r = getRow(loc)
        r = loc.row;
    end

    function c = getCol(loc)
        c = loc.col;
    end
    function display(loc)
        disp('row: ')
        disp(loc.row)
        disp('col: ')
        disp(loc.col)
    end
end

Grid class, child of location:

classdef Grid < Location
properties
    grid;
end
methods
    function gr = Grid(rows, cols)
        if nargin > 0
            gr.grid = cell(rows,cols);
        end
    end

    function nrows = getNumRows(gr)
        [nrows,ncols] = size(gr.grid);
    end

    function ncols = getNumCols(gr)
        [nrows,ncols] = size(gr.grid);
    end

    function put(gr,act,loc)
        gr.grid{loc.getRow,loc.getCol} = act;
    end

    function act = get(gr,loc)
        act = gr.grid{loc.getRow(),loc.getCol()};
    end
end

Finally, the test commands from the command window

testLoc = Location(1,2)

row: 1

col: 2

testGrid = Grid(3,4) row: col: testGrid.put('testStr',testLoc) testGrid.get(testLoc)

ans =

[]

testGrid.grid{1,2} = 'newTest' row: col: testGrid.get(testLoc)

ans =

newTest

Thanks for any insight!

Was it helpful?

Solution

You need to return the object from your functions and use that as your new object. So

function put(gr,act,loc)
    gr.grid{loc.getRow,loc.getCol} = act;
end

Should be

function gr = put(gr,act,loc)
    gr.grid{loc.getRow,loc.getCol} = act;
end

And then you can use it like

testGrid = Grid(3,4)
testGrid = testGrid.put(act, loc)
testGrid.get(loc)

And you can also chain the calls

testGrid.put(act, loc).get(loc)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top