How to turn a multivariable function to multidimensional x-function?

So what I want to do is turn an n-dimensional function, for example
f=@(x,y,z)x+y+z+t
to a function which contains only x:s. I'd do this by hand as
f2=@(x)f(x(1),x(2),x(3),x(4))
I'll also have a point at my disposal as a vector, so that will be most likely the easiest way to find the amount of new variables needed. So here's what I've tried:
p=[1 4 6 2]
f=@(x,y,z,t)x+y+z+t
text=[]
for i=1:length(p)-1
A=['x(',num2str(i),'),']
text=[text,A]
end
for i=length(p):length(p)
A=['x(',num2str(i),')']
text=[text A]
end
f2=@(x)f(text)
f2(p)
Of course doing this with "if" would be possible, but i think that's just too heavy way of doing it. So, has anybody an idea, or is it even possible, to make this happen: f2=@(x) x(1)+x(2)+x(3)+x(4)

Réponses (1)

The varargin (link) function is an option:
f = @(varargin) sum(varargin{:});
x = [42 pi];
Out_1 = f(x)
z = 1:5;
Out_2 = f(z)
Out_1 =
45.142
Out_2 =
15
Of course, whether this is appropriate depends on what you want to do in your function.

4 commentaires

nassu100’s ‘Answer’ moved here:
The f2(p) is there only for testing purposes. I'll be using this for a function which calculates gradient in a specific point, and it'll be using a numeric derivative-function, which needs input as x(1),x(2) etc. The function works, if I give it the function as an x-function, but just to refine it, I'd like to be able to give it function with normal variables.
The varargin approach will likely do what you want.
Example
g = @(varargin) varargin{1} .* exp(varargin{2} * varargin{3});
Out_3 = g([1; 2], -0.5, 0:0.1:0.5)
Out_3 =
1 0.95123 0.90484 0.86071 0.81873 0.7788
2 1.9025 1.8097 1.7214 1.6375 1.5576
It doesn't like I hope it to do. There are two parts:
-it has to be n-scaling, depending on the length of the p (or the amount of variables given in, which are the same)
-it has to return a function of an x-variable, which i can import to a function file
I know I can always use Matlab's own gradient-function to calculate the partial derivatives for me, but that's not the case.
O.K.
I don’t know what you want to do. This is the best I can do.
Since my Answer doesn’t solve your problem, I’ll delete it in a while.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Mathematics dans Centre d'aide et File Exchange

Question posée :

le 24 Mar 2018

Commenté :

le 24 Mar 2018

Community Treasure Hunt

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

Start Hunting!

Translated by