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

前端 未结 9 1655
盖世英雄少女心
盖世英雄少女心 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 06:01

    Your initial notation is the most concise way to do this:

    M = magic(5);  %create
    value = M(3,3);  % extract useful data
    clear M;  %free memory
    

    If you are doing this in a loop you can just reassign M every time and ignore the clear statement as well.

    0 讨论(0)
  • 2020-11-21 06:04

    At least in MATLAB 2013a you can use getfield like:

    a=rand(5);
    getfield(a,{1,2}) % etc
    

    to get the element at (1,2)

    0 讨论(0)
  • 2020-11-21 06:09

    It actually is possible to do what you want, but you have to use the functional form of the indexing operator. When you perform an indexing operation using (), you are actually making a call to the subsref function. So, even though you can't do this:

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

    You can do this:

    value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}}));
    

    Ugly, but possible. ;)

    In general, you just have to change the indexing step to a function call so you don't have two sets of parentheses immediately following one another. Another way to do this would be to define your own anonymous function to do the subscripted indexing. For example:

    subindex = @(A, r, c) A(r, c);     % An anonymous function for 2-D indexing
    value = subindex(magic(5), 3, 3);  % Use the function to index the matrix
    

    However, when all is said and done the temporary local variable solution is much more readable, and definitely what I would suggest.

    0 讨论(0)
提交回复
热议问题