How do I make my variables save from my function?

1 回表示 (過去 30 日間)
Sarah Johnson
Sarah Johnson 2020 年 2 月 19 日
編集済み: Sabin Thapa 2021 年 2 月 17 日
I have written a function function [f, grad, gradTwo] = Rosen(x), which returns the Rosenbrock function value f(x) to f, its gradient vector ∇f(x) to grad, and its Hessian matrix ∇f(x) to gradTwo, at the given input point x and verify the function returns correct values.
I have written a function that does so, using x = [1, 1], but my values don't store.
function [f, grad, gradTwo] = Rosen(x)
g = @(x)100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;
f = g(x);
grad = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1)); 200*(x(2)-x(1)^2)];
gradTwo = [800*x(1)+2, -400*x(1); -400*x(2), 200];
end
Then my output when I run this is:
ans =
0
I believe my professor wants it to look like this:
f =
0
grad =
0
0
gradTwo =
802 -400
-400 200
Is there a way to accomplish this? Any advice would be great, I'm not that great at MATLAB
  1 件のコメント
Sabin Thapa
Sabin Thapa 2021 年 2 月 17 日
編集済み: Sabin Thapa 2021 年 2 月 17 日
Hi, if grad = ∇f(x) and gradTwo = ∇^2 f(x), then these should be:
grad = [400*x(1)^3 - 400*x(1)*x(2) + 2*x(1) - 2; 200*(x(2)-x(1)^2)];
and gradTwo = [1200*x(1)^2 - 400*x(2) + 2, -400*x(1); -400*x(1), 200];
(related to mathematics, not coding)

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

採用された回答

Hiro Yoshino
Hiro Yoshino 2020 年 2 月 19 日
You're doing well!
Try this:
x = [1 1];
[f, grad, gradTwo] = Rosen(x)
You should prepare the three variables that recieve the calculus!
  1 件のコメント
Sarah Johnson
Sarah Johnson 2020 年 2 月 19 日
Thank you so much!!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by