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

조회 수: 5 (최근 30일)
nassu100
nassu100 2018년 3월 24일
댓글: Star Strider 2018년 3월 24일
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)

답변 (1개)

Star Strider
Star Strider 2018년 3월 24일
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
nassu100
nassu100 2018년 3월 24일
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 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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by