How to solve an equation with 2 variables where one variable is inputed?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Nicolas Karmolinski
el 12 de Feb. de 2020
Comentada: Star Strider
el 12 de Feb. de 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?
Thank you in advance,
Nicolas
0 comentarios
Respuesta aceptada
Star Strider
el 12 de Feb. de 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.
3 comentarios
Steven Lord
el 12 de Feb. de 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)
Star Strider
el 12 de Feb. de 2020
@Nicolas Karmolinski — As always, my pleasure!
@Steven Lord — Thank you!
Más respuestas (0)
Ver también
Categorías
Más información sobre Optimization en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!