# How to solve an equation with 2 variables where one variable is inputed?

6 views (last 30 days)
Nicolas Karmolinski on 12 Feb 2020
Commented: Star Strider on 12 Feb 2020
Hello all,
I have a function which depends on 2 variables. I would like to write a script in which I input the value of one of the variables, and then MATLAB solves for the other variable. However, the function is non-linear so I believe using the fsolve command would be the best. This is the script that I have written so far:
clear all
clc
r = input('Range of the target')
fun = @BallRange;
angle = fsolve(fun,60)
function R = BallRange(r,x)
R = r*sin(2*x) + 0.7*(cos(x)^2) - 0.176275*r^2
end
However, I get multiple error codes when I try to run the program.
How can I change the code so I can get the desired output (angle)?
Furthermore, would it be possible to make an algorithm to plot a function with r on the x-axis ranging from 2 to 6 with increments of 0.1 and the corresponding angle on the y-axis?
Nicolas

Star Strider on 12 Feb 2020
Try this:
BallRange = @(r,x) r.*sin(2*x) + 0.7*(cos(x).^2) - 0.176275*r.^2;
r = input('Range of the target ')
angle = fsolve(@(x)BallRange(r,x),60)
It returns values very close to the initial estimate, regardless of what ‘r’ is.

Nicolas Karmolinski on 12 Feb 2020
Thank you very much
Steven Lord on 12 Feb 2020
Since there's only one scalar variable for which you're solving (x, since r is fixed) you could use fzero (included in MATLAB) instead of fsolve (included in Optimization Toolbox.)
In addition, you can avoid the need to create two anonymous functions and just create one if you reorder the lines of code. Though if you want to ask for ranges repeatedly and reuse BallRange, the approach Star Strider used would avoid having to keep recreating it.
r = input('Range of the target ');
BallRange = @(x) r.*sin(2*x) + 0.7*(cos(x).^2) - 0.176275*r.^2;
A = fsolve(BallRange, 60)
Finally, angle already has a meaning in MATLAB.
Star Strider on 12 Feb 2020
@Nicolas Karmolinski — As always, my pleasure!
@Steven Lord — Thank you!