How to write a symbolic function array?

function f=g5(x)
syms q b x
q=[6 7 1;7 11 2;1 2 22]
b=[-1;2;3]
x=transpose(sym('x',[1 3]))
f=1/2*transpose(x)*q*x+transpose(b)*x-2
end
This is my writing function
clc;
clear;
%%gradient descent
syms w
w=[2;2;6]
for i=1:30
w=w-5*gradient(g5(w))
%%if norm(gradient(g5(w)))>0.01
%%break
%%end
display(w)
end
This is the variable I setted trying to find the solution of the function. But the outcome is
w =
152 - 1050*x2 - 150*x3 - 900*x1
- 1050*x1 - 1650*x2 - 300*x3 - 298
- 150*x1 - 300*x2 - 3300*x3 - 444
I want to insert [2;2;6] into [x1;x2;x3] to get the value of the function. But it seems symbolic variables defined cannot be taken as parameters. Is there any way to change it into independent variables?

6 件のコメント

Walter Roberson
Walter Roberson 2020 年 11 月 5 日
syms q b x
That is equivalent to
q = sym('q');
b = sym('b');
x = sym('x');
and that is going to ovewrite the x that was passed in to the function
function f=g5(x)
so anything you pass in to the function is going to be ignored.
Zhenwei Yu
Zhenwei Yu 2020 年 11 月 6 日
@Walter Roberson
So anyway I can do this? I tried using syms q b only without x. not working though. Or I simply left out function f=g5(x)?
Walter Roberson
Walter Roberson 2020 年 11 月 6 日
function f=g5(x)
q = [6 7 1;7 11 2;1 2 22];
b = [-1;2;3];
f = 1/2*x'*q*x + b'*x - 2
end
The result will already be a scalar, so you would not take gradient() or norm() of it.
Zhenwei Yu
Zhenwei Yu 2020 年 11 月 6 日
function f=g5(x)
q = [6 7 1;7 11 2;1 2 22];
b = [-1;2;3];
f = 1/2*x'*q*x + b'*x - 2
end
Not enough input arguments.
Error in g5 (line 4)
f = 1/2*x'*q*x + b'*x - 2
I don't know why but this get an error
@Walter Robertson
Walter Roberson
Walter Roberson 2020 年 11 月 6 日
w=[2;2;6];
g5(w)
ans = 512
function f=g5(x)
q = [6 7 1;7 11 2;1 2 22];
b = [-1;2;3];
f = 1/2*x'*q*x + b'*x - 2;
end
Looks okay to me.
Zhenwei Yu
Zhenwei Yu 2020 年 11 月 6 日
@Walter Roberson
Thanks for your help but it seems you may misunderstand my purpose. I got a function 1/2*x'*q*x + b'*x - 2, and I need to calculate its gradient. Something like (3x1+7x2+x3,7/2x1+11/2x2...). And use values in each point of gradient function to make it close to optimal point.
Your function is right and I just tested. But it seems I cannot preserve the unknown variables for further calculation

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

回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMathematics についてさらに検索

製品

リリース

R2020b

質問済み:

2020 年 11 月 5 日

コメント済み:

2020 年 11 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by