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

前端 未结 9 1839
盖世英雄少女心
盖世英雄少女心 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条回答
  •  萌比男神i
    2020-11-21 05:42

    To complement Amro's answer, you can use feval instead of builtin. There is no difference, really, unless you try to overload the operator function:

    BUILTIN(...) is the same as FEVAL(...) except that it will call the original built-in version of the function even if an overloaded one exists (for this to work, you must never overload BUILTIN).

    >> feval('_paren', magic(5), 3, 3)               % M(3,3)
    ans =
        13
    
    >> feval('_brace', num2cell(magic(5)), 3, 3)     % C{3,3}
    ans =
        13
    

    What's interesting is that feval seems to be just a tiny bit quicker than builtin (by ~3.5%), at least in Matlab 2013b, which is weird given that feval needs to check if the function is overloaded, unlike builtin:

    >> tic; for i=1:1e6, feval('_paren', magic(5), 3, 3); end; toc;
    Elapsed time is 49.904117 seconds.
    >> tic; for i=1:1e6, builtin('_paren', magic(5), 3, 3); end; toc;
    Elapsed time is 51.485339 seconds.
    

提交回复
热议问题