How to turn a multivariable function to multidimensional x-function?
Show older comments
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
on 24 Mar 2018
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
Star Strider
on 24 Mar 2018
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.
Star Strider
on 24 Mar 2018
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
nassu100
on 24 Mar 2018
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.
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!