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

조회 수: 6 (최근 30일)
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

채택된 답변

Star Strider
Star Strider 2020년 2월 12일
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
Steven Lord
Steven Lord 2020년 2월 12일
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
Star Strider 2020년 2월 12일
@Nicolas Karmolinski — As always, my pleasure!
@Steven Lord — Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by