How to turn a multivariable function to multidimensional x-function?
5 次查看(过去 30 天)
显示 更早的评论
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)
0 个评论
回答(1 个)
Star Strider
2018-3-24
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 个评论
Star Strider
2018-3-24
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!