ChatGPT解决这个技术问题 Extra ChatGPT

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

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 value == 13. I'd like to be able to do something like one of these:

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

to dispense with the intermediate variable. However, MATLAB complains about Unbalanced or unexpected parenthesis or bracket on the first parenthesis before the 3.

Is it possible to read values from an array/matrix without first assigning it to a variable?

I also found the following article on this theme: mathworks.com/matlabcentral/newsreader/view_thread/280225 Anybody has new information on this theme, will it be implemented?
This syntax actually works fine in Octave. I only discovered this issue when my colleagues who use MATLAB were having issues running my code.
MATLAB in a nutshell.
Recursive extraction also works in Scilab (scilab.org) since version 6.
the testmatrix('magi', 5)(3, 3) on Scilab and magic(5)(3, 3) on Octave both work like a charm!

g
gnovice

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.


well what do you know! though i agree it's pretty ugly, and probably less readable than a temp-var solution. +1 for impressive obscure matlab knowledge!
That's disgusting, but a very clear answer. Good work! Should've guessed there'd be a back way into it. I'll think I'll carry on with the temp variable.
Bear in mind that the intermediate variable is still fully created though. So if the purpose is to save memory by not having to create a temporary local variable, no luck.
@SamRoberts: You can't really get around that in a strict-evaluation language like Matlab. The main reason people want this is conciseness/readability, not memory savings.
@SamRoberts: true, but it does save you from the burden of calling clear on the temporary (which no-one ever does) -- the temporary tends to stick around longer
n
nekomatic

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.


This is a slightly more general version of the second half of gnovice's answer; also good.
What about myfunc().attr?
@gerrit, how does at help? and the x.attr() field isn't available unless you have the database toolbox.
@T.Furfaro Huh? If myfunc() returns a structure that includes an attribute attr, then to access attr currently I need to do S = myfunc(); S.attr. The question is if we can have a helper function like getattr(myfunc(), 'attr') in analogy to the paren and curly helpers. I don't understand what this has to do with the database toolbox.
@gerrit Sorry, total confusion ( I wasn't aware that your "attr" was arbitrary -- in the db tb there's such a field explicity defined ). I believe what you're looking for is getfield()
A
Amro

How do you feel about using undocumented features:

>> builtin('_paren', magic(5), 3, 3)               %# M(3,3)
ans =
    13

or for cell arrays:

>> builtin('_brace', num2cell(magic(5)), 3, 3)     %# C{3,3}
ans =
    13

Just like magic :)

UPDATE:

Bad news, the above hack doesn't work anymore in R2015b! That's fine, it was undocumented functionality and we cannot rely on it as a supported feature :)

For those wondering where to find this type of thing, look in the folder fullfile(matlabroot,'bin','registry'). There's a bunch of XML files there that list all kinds of goodies. Be warned that calling some of these functions directly can easily crash your MATLAB session.


@RodyOldenhuis: I dont recall now, I guess I must have read it in some buried code ;)
The colon (:) operator must be used with apostrophes ':' to avoid the error Undefined function or variable "builtin".
@Dominik: right, say you want to slice the 2nd column, that would be: builtin('_paren', magic(5), ':', 2) (in certain places it does work without the quotations directly as : as opposed to ':', like when running in the command prompt directly not from inside a function. I guess that's a bug in the parser!)
I don't suppose there is some way to use end with this?
@knedlsepp: No, unfortunately the whole end-trickery doesn't work in this syntax, you'll have to be explicit in your indexing.. (Same limitation applies for most other listed answers)
C
Cris Luengo

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)


This is actually a nice method. Any drawbacks?
@mmumboss: That's undocumented behaviour, this functionality may disappear without notice in future versions. Besides this no disadvantages.
As of MATLAB2017b, this functionality is documented.
How do I get a column or a row of the output? Such as a(1, :). I've tried getfield(rand(5), {1, 1:5}) and getfield(rand(5), {1:5, 1}) which work fine, but are not elegant.
@ZRHan: You can use getfield(rand(5), {1, ':'})
s
second

unfortunately syntax like magic(5)(3,3) is not supported by matlab. you need to use temporary intermediate variables. you can free up the memory after use, e.g.

tmp = magic(3);
myVar = tmp(3,3);
clear tmp

u
user

Note that if you compare running times with the standard way (asign the result and then access entries), they are exactly the same.

subs=@(M,i,j) M(i,j);
>> for nit=1:10;tic;subs(magic(100),1:10,1:10);tlap(nit)=toc;end;mean(tlap)

ans =

0.0103

>> for nit=1:10,tic;M=magic(100); M(1:10,1:10);tlap(nit)=toc;end;mean(tlap)

ans =

0.0101

To my opinion, the bottom line is : MATLAB does not have pointers, you have to live with it.


S
Shai

It could be more simple if you make a new function:

function [ element ] = getElem( matrix, index1, index2 )
    element = matrix(index1, index2);
end

and then use it:

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

but this is exactly what subref does... but in a more general way.
yes, more general way, but not friendly... to much ugly in my opinion.
A
Andreas GS

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.


I agree that this is more concise, and clearing is a good idea in a loop, as you say, but the question was specifically whether the intermediate assignment can be avoided.
The clear statement will significantly slow down your code, it's better to leave it out unless M is terribly big and you're running out of memory somewhere.
@JoeKearney understood. Perhaps it's my novice level of Matlab, but intermediate values are computed in every answer given, if only implicitly in some. Is that correct? In any case, thanks for the feedback!
n
nirvana-msu

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.

It is actually not strange: MATLAB keeps a list of defined functions, there is not that much searching to do. feval does the “normal” thing and therefore can make full use of this list. builtin must search elsewhere so it finds only built in functions. Likely this case is not optimized nearly as much as the “normal” case, because why would you put money into optimizing something not used very often?

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now