How can I index a MATLAB array returned by a function without first assigning it to a local variable?

前端 未结 9 1684
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:02

For example, if I want to read the middle value from magic(5), I can do so like this:

M = magic(5);
value = M(3,3);

to get

9条回答
  •  星月不相逢
    2020-11-21 05:48

    There was just good blog post on Loren on the Art of Matlab a couple days ago with a couple gems that might help. In particular, using helper functions like:

    paren = @(x, varargin) x(varargin{:});
    curly = @(x, varargin) x{varargin{:}};
    

    where paren() can be used like

    paren(magic(5), 3, 3);
    

    would return

    ans = 16
    

    I would also surmise that this will be faster than gnovice's answer, but I haven't checked (Use the profiler!!!). That being said, you also have to include these function definitions somewhere. I personally have made them independent functions in my path, because they are super useful.

    These functions and others are now available in the Functional Programming Constructs add-on which is available through the MATLAB Add-On Explorer or on the File Exchange.

提交回复
热议问题