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

5 views (last 30 days)
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)

Answers (1)

Star Strider
Star Strider on 24 Mar 2018
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 Comments
nassu100
nassu100 on 24 Mar 2018
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.
Star Strider
Star Strider on 24 Mar 2018
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.

Sign in to comment.

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!