Query output dimension of function handle

8 visualizaciones (últimos 30 días)
Lukas-Benedikt Fiechtner
Lukas-Benedikt Fiechtner el 17 de Mayo de 2017
Comentada: Steven Lord el 18 de Mayo de 2017
Suppose I have the following two function handles:
f1 = @(x,y)[x+y, x*y];
f2 = @(x,y)[1,x,y,x^2,x*y, y^2]
Is there a way to query the dimension of the output of a specific function handle, i.e. in my example I want to get the answer "2" for f1 and the answer "6" for f2, since the first one maps to R^2 and the second to R^6.
Thanks in advance!
  3 comentarios
Lukas-Benedikt Fiechtner
Lukas-Benedikt Fiechtner el 17 de Mayo de 2017
Yes, that works of course. But sometimes I might also want to modify the number of inputs. Hence I must always know the number of input arguments which might not always be the case.
Steven Lord
Steven Lord el 18 de Mayo de 2017
Let's say there was a function, call it sizeOfOutput, that accepts an anonymous function and returned the size of its output arguments (without executing that anonymous function.) What would you expect it to return for this?
f = @(n) zeros(n);
Or this?
g = @(n) zeros(randi([1 n], 2));
Or how about an anonymous function that accepts a file name and returns data read from that file?

Iniciar sesión para comentar.

Respuestas (1)

Cam Salzberger
Cam Salzberger el 17 de Mayo de 2017
Editada: Cam Salzberger el 17 de Mayo de 2017
This is a good question, but it doesn't quite work with the way that MATLAB defines arrays or anonymous functions. Your question is assuming that you are inputting scalars into the anonymous function, which your code may very well do. However, MATLAB only knows about the function handle. For example, if I take the simple function:
f = @(x)[x,2*x];
and then call it with:
f(ones(1,2))
I'll get a 1x4 array output. So there's really no way to know what the output will be in these types of cases without knowing the input, and running the function on the input to see what happens.
Your comment, however, mentions that you are looking to modify the number of input arguments. That is pretty simple, you can just use "nargin":
nargin(f1)
This will tell you how many input arguments the anonymous function is expecting.
-Cam

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by