Passing Symbolic Variables into a function as parameters

68 ビュー (過去 30 日間)
Benjamin Colety
Benjamin Colety 2020 年 5 月 6 日
コメント済み: Ameer Hamza 2020 年 5 月 7 日
I am trying to write a function that takes 2 symbolic equations, as well as the symbolic variables to solve for, in as parameters. The function is then supposed to solve for the 2 symbolic variables and then eliminate any solutions that contain imaginary numbers as you can see below.
syms x y
f = (x*y) == 1;
g = (x)+y == 0;
solution = testfunct(f, g, {x}, {y})
function [sols1 sols2] = testfunct(eq1, eq2 , t, s)
sols = solve(eq1, eq2, [t s]);
sols1 = sols.t(imag(sols.t)==0); % "Reference to non-existent field 't'"
sols2 = sols.s(imag(sols.s)==0);
end
I receive an error saying seen in the comment. Now if this code works if I replace that line with
sols1 = sols.x(imag(sols.x)==0); %and the same for sols2 replacing x with y
Running whos gives me that t is a cell containing 1x1 sym which is x so I tried
sols1 = sols.(t{1,1})
which returns an error saying that 'Argument to dynamic structure reference must evaluate to a valid field name.' Even though t{1,1} = x and class(t{1}) = 'sym'.

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 5 月 6 日
If you are willing to use the same variable name inside the function, then you can try this
syms x y
f = (x*y) == 1;
g = (x)+y == 0;
solution = testfunct(f, g, x, y) % <==== no need to pass as cell
function [sols1 sols2] = testfunct(eq1, eq2 , x, y)
sols = solve(eq1, eq2, [x y]);
sols1 = sols.x(imag(sols.x)==0); % "Reference to non-existent field 't'"
sols2 = sols.y(imag(sols.y)==0);
end
If you want to use t and s as input variables, then you can use the following syntax
syms x y
f = (x*y) == 1;
g = (x)+y == 0;
solution = testfunct(f, g, x, y) % <==== no need to pass as cell
function [sols1 sols2] = testfunct(eq1, eq2 , t, s)
sols = solve(eq1, eq2, [t s]);
t_char = char(t);
s_char = char(s);
sols1 = sols.(t_char)(imag(sols.(t_char))==0); % "Reference to non-existent field 't'"
sols2 = sols.(s_char)(imag(sols.(s_char))==0);
end
  2 件のコメント
Benjamin Colety
Benjamin Colety 2020 年 5 月 7 日
Thanks!
Ameer Hamza
Ameer Hamza 2020 年 5 月 7 日
I am glad to be of help.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by