【问题标题】:Assign value to cell array through function MATLAB通过函数 MATLAB 为元胞数组赋值
【发布时间】:2014-04-19 02:24:15
【问题描述】:

我正在尝试使用 matlab 粗略地实现 AP CS 'gridworld',尽管类更少。到目前为止,我有一个具有属性 row 和 col 的超类“位置”。接下来我有一个“网格”,只有一个名为网格的单元格数组。使用 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

col: 2

testGrid = Grid(3,4) 排: 上校: testGrid.put('testStr',testLoc) testGrid.get(testLoc)

ans =

[]

testGrid.grid{1,2} = 'newTest' 排: 上校: testGrid.get(testLoc)

ans =

新测试

感谢您的任何见解!

【问题讨论】:

    标签: matlab function cell-array


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 我没有意识到您必须将函数的输出重新分配给同一个 testGrid(基本上用新的 testGrid 完全重写 testGrid,对象位于 loc)谢谢!
    猜你喜欢
    • 2016-08-01
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    相关资源
    最近更新 更多