Clear Filters
Clear Filters

Solving non linear equation with a range in MATLAB (problem)

7 views (last 30 days)
I need to solve below non-linear equation with a range but cannot find a way to do it
Range of (x) is -40 to 30 with increments of 5. (x) is known but I need to find range of (y) and plot (x) vs (y). Please with the answer provide an explanation also. Thank you
p=0.5
S=(sin(y-x)-p*sin(x)*sin(y))=0

Accepted Answer

JK
JK on 7 Feb 2018
Hi Abdullah,
here is the code with comments:
x=[-40:5:30]'; % x in rad or °? Matlab uses rad
n = size(x,1); % numbers of calculations
yy=zeros(n,1); % preallocation of yy to make it a column-vector
for i=1:n
yy(i)=fsolve(@(y) fun(x(i),y),0); % solve implicit equation
end
figure
plot(x,yy) % plot it
function S=fun(x,y)
S=(sin(y-x)-0.5*sin(x)*sin(y)); % your function
end
  4 Comments
JK
JK on 7 Feb 2018
yy(i)=fsolve(@(y) fun(x(i),y),0);
  • yy(i) is y(x(i))
  • fsolve is the solver for implicit equations, it solves f(x)=0 for x. You can also use fzero is this case which is probably faster.
  • @(y) fun(x(i),y) is an anonymus function. I uses the x(i) value by the time it is called and solves the function fun(x,y) for y.
  • 0 is the initial guess for y. For a simple equation, 0 will normally suffice as a starting point. If the equation gets more complicated try better starting values.
for using ° instead of rad try
x=[-40:5:30]'/180*pi;
...
plot(x/pi*180,yy/pi*180)

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 7 Feb 2018
syms x y
p = 0.5;
eq = (sind(y-x)-p*sind(x)*sind(y)) == 0;
Y = simplify(solve(eq, x));
This gives you an explicit formula for Y. You can substitute particular numeric values for x into the formula.
MATLAB will return two expressions. If you analyze the expressions, they turn out to differ by 180 degrees. Further analysis shows that there an an infinite number of other solutions that are 180 apart.
  3 Comments
Walter Roberson
Walter Roberson on 7 Feb 2018
Do not assign numeric values to x before the code that follows.
xvec = -40:5:30;
syms x y
p = 0.5;
eq = (sind(y-x)-p*sind(x)*sind(y)) == 0;
Y = simplify(solve(eq, y)); %typo fixed on this line
Yn = double( subs(Y, x, xvec) );
plot(xvec, real(Yn));

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!