MATLAB: F(x) = e^x-3x matlab code

functionMATLAB

I want to write a matlab script that finds solutions of function f(x) = e^x – 3x. I tried to write some code. My matlab code should include iteration table and graphic of function. Can anyone help me please with a code or give me advices?
f=@(x) exp(x) - 3*x ;
a = 0; b = 1;tol = 1e-8;
if (f(a)*f(b) > 0)
error ('invalid choice of interval')
end
r=0; n=0;
while ((b-a)/2 > 0)
n = n + 1;
r = (a+b)/2;
if (f(r) == 0)
break;
elseif (f(a)*f(r) <= 0)
b = r ;
else
a = r;
end
end

Best Answer

Hi Adomas Bazinys
What you want to do is, the way you want to do it, indeed good exercise, but
1.
What about fsolve
At Mathworks the function fsolve was time ago developed precisely so that the people using MATLAB could save time avoiding the need for any writing of such functions, and go straight to the roots, have a look:
fun = @(x) exp(x)-3*x;
x0 = [1.5,0];
x = fsolve(fun,x0)
x =
1.512134551657842 0.619061283355628
2.
Don't start with x0=[0 0] or [1 0] because then fsolve only returns a single real solution
3.
The requested graph
fplot(fun);grid on
.
4.
And the table
x_range1=0;x_range2=10;xrange_step=1;
x1=[x_range1:xrange_step:x_range2]';fx1=fun(x1);
T1=table(x1,fx1)
T1 =
11×2 table
x1 fx1
__ __________________
0 1
1 -0.281718171540954
2 1.38905609893065
3 11.0855369231877
4 42.5981500331442
5 133.413159102577
6 385.428793492735
7 1075.63315842846
8 2956.95798704173
9 8076.08392757538
10 21996.4657948067
I assumed you ask for a MATLAB table.
You can also export this table to Excel, Word or a simple .txt file, if you choose to call those the intended tables to hold the result.
5.
Checking the 4 limits +- Inf +-1j*Inf
syms n;limit(exp(n)-3*n, n, -inf)
=
Inf
syms n;limit(exp(n)-3*n, n, inf)
=
Inf
syms n;limit(exp(1j*n)-3*1j*n, n, inf)
=
NaN
syms n;limit(exp(1j*n)-3*1j*n, n, -inf)
=
NaN
Do you really need considering exp(1j*imx)-3*1j*imx ?
If so the start point is
exp(1j*imx)-3*1j*imx = cos(imx)+1j*(sin(imx)-3*imx)
this would be when real(x)>>imx=imag(x)
6.
the 2 real roots found with fsolve probably turn into a corona of complex roots that may be appreciated developing a bit further the following start point.
rangelim=15;rangestep=.01;
rex=[-rangelim:rangestep:rangelim];
imx=[-rangelim:rangestep:rangelim];
[RX,IX]=meshgrid(rex,imx);
Z=exp(RX+1j*IX)-3*(RX+1j*IX);
figure(2);hs=surf(abs(Z),RX,IX);hs.EdgeColor='none';
Adomas
If interested in the complex roots, please let me know.
If you find the so far supplied answer useful, would you please be so kind to consider marking my answer as Accepted Answer?
To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
thanks in advance
John BG