通过函数MATLAB为单元数组赋值

时间:2014-04-19 02:24:16

标签: matlab function cell-array

我试图粗略地实施AP CS' gridworld'使用matlab,albiet,课程较少。到目前为止,我有一个超级班级'位置'使用属性row和col。接下来我有' Grid'只有一个名为grid的单元格数组。使用Grid.get命令,我可以从该单元格数组中检索对象。但问题是,我无法使Grid.put函数工作。不使用该函数进行测试允许我将测试字符串放入testGrid.grid {},但该函数似乎不起作用。

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

网格类,位置的孩子:

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

最后,来自命令窗口的测试命令

  
    

testLoc =位置(1,2)

  

行:      1

西:      2

  
    

testGrid = Grid(3,4)     行:     西:     testGrid.put(&#39; testStr&#39;,testLoc)     testGrid.get(testLoc)

  

ans =

[]

  
    

testGrid.grid {1,2} =&#39; newTest&#39;     行:     西:     testGrid.get(testLoc)

  

ans =

newTest

感谢您的任何见解!

1 个答案:

答案 0 :(得分:0)

您需要从函数中返回对象并将其用作新对象。所以

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

应该是

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

然后你可以像

一样使用它
testGrid = Grid(3,4)
testGrid = testGrid.put(act, loc)
testGrid.get(loc)

你也可以连接电话

testGrid.put(act, loc).get(loc)