How to parameterise a function?

6 ビュー (過去 30 日間)
Jennifer Wail
Jennifer Wail 2015 年 6 月 4 日
編集済み: Stephen23 2015 年 6 月 4 日
I was trying to use a multi-variable function in commands that take functions as inputs but kept getting errors and was told to parameterise the function but not sure how. The function is f(x,y,z) = x^2 + 3y^2 + 4z^2 - 2xy + 5x - 3y + 2z. I tried doing:
f = @(x,y,z) = x.^2 + 3.*y.^2 + 4.*z.^2 - 2.*x.*y + 5.*x - 3.*y + 2.*z;
ezplot(f)
fminsearch(f,[0,0,0])
and was told to parameterise my functions so that x(1)=x, x(2)=y... Not sure how to continue though. Please help

採用された回答

Stephen23
Stephen23 2015 年 6 月 4 日
編集済み: Stephen23 2015 年 6 月 4 日
The standard answer is to replace each x, y and z with the corresponding element of the input vector:
g = @(V) = V(1).^2 + 3.*V(2).^2 + 4.*V(3).^2 - 2.*V(1).*V(2) + 5.*V(1) - 3.*V(2) + 2.*V(3);
A more readable alternative is to use two functions, which allows you to keep the original function unchanged. This could be useful if it is important to keep exactly the same equation as some reference, or to use exactly those variables names, or just to maintain readability:
f = @(x,y,z) = x.^2 + 3.*y.^2 + 4.*z.^2 - 2.*x.*y + 5.*x - 3.*y + 2.*z;
g = @(V) f(V(1),V(2),V(3));
and then call the function g in all of your following work. It has the disadvantage that it would likely be a smidgen slower, so do not use this if your need to perform millions of iterations.
  1 件のコメント
Jennifer Wail
Jennifer Wail 2015 年 6 月 4 日
Thank you that did get me further but now having trouble with fminsearch
f = @(x) x(1)^2 + 3*x(2)^2 + 4*x(3)^2 - 2*x(1)*x(2) + 5*x(1) - 3*x(2) + 2*x(3)
[x fval] = fminsearch(f,[0,0,0])
Maybe I'll post a second question on that but thank you again you helped me get further on other problems with that

サインインしてコメントする。

その他の回答 (1 件)

James Tursa
James Tursa 2015 年 6 月 4 日
編集済み: James Tursa 2015 年 6 月 4 日
Do pretty much exactly what the advice says:
f = @(x) x(1)^2 + 3*x(2)^2 + 4*x(3)^2 - 2*x(1)*x(2) + 5*x(1) - 3*x(2) + 2*x(3);
  1 件のコメント
Jennifer Wail
Jennifer Wail 2015 年 6 月 4 日
I tried that but now fminsearch gives me index out of bounds error

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by