Access a single element of an anonymous function that returns an array

23 vues (au cours des 30 derniers jours)
Leo Simon
Leo Simon le 27 Avr 2014
Commenté : Stephen23 le 20 Avr 2020
I have an anonymous function that returns an array. I'd like to be able to create a new anonymous function that consists of a single element of this array WITHOUT using matlabfunction (which is infuriatingly restrictive in several respects).
For example, consider the following code (it's a ridiculously simple example, for expository purposes, obviously there are easy ways of dealing with this example, but my real problem is more complex)
y = sym('y',[1,4])
f = @(y)[y(1);y(2);y(3);y(4)]
f(y)
which returns
ans =
y1
y2
y3
y4
I'd now like to define a new anonymous function which extracts, say, the third element of this array. Obviously,
g = @(y) f(y)(3)
won't work. Is there some way to accomplish this? Again, solns involving matlabfunction are not satisfactory.
Any suggestions would be most appreciated!
Leo

Réponse acceptée

Walter Roberson
Walter Roberson le 27 Avr 2014
indexat = @(expr, index) expr(index);
g = @(y) indexat(f(y), 3);
  2 commentaires
Leo Simon
Leo Simon le 27 Avr 2014
Fabulous, thanks very much Walter, works beautifully
Stephen23
Stephen23 le 7 Avr 2020
"could you please explain what you mean by "expr" and "index"? "
They are the input arguments of an anonymous function:

Connectez-vous pour commenter.

Plus de réponses (1)

Lauren Barr
Lauren Barr le 20 Avr 2020
This is really helpful, thank you! I was wondering if there is a way to extend it, so that I can index one particular value in a 2D matrix, instead of indexing into a vector?
For example, this doesn't seem to work:
indexat = @(expr, index) expr(index);
g = @(y) indexat(f(y), (1,3));
But maybe I am missing something obvious.
Thank you!
Lauren
  2 commentaires
Stephen23
Stephen23 le 20 Avr 2020
You can create a general solution for any number of dimensions:
indexat = @(expr, varargin) expr(varargin{:});

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by