views:

48

answers:

1

Hello! I have a homework problem, I think I did it correctly but need to make sure 100%. Can anyone check for me, before I hand it in? Thank you.

Question: Plot the function given by f (x) = 2 sin(2x) − 3 cos(x/2) over the in- terval [0, 2π] using steps of length .001 (How?). Use the commands max and min to estimate the maximum and minimum points. Include the maximum and minimum points as tick marks on the x-axis and the maximum and minimum values as tick marks on the y-axis.

My code:

x=linspace(0,2*pi,6280);
f=@(x)...
    2.*sin(2.*x)-3.*cos(x./2);

%f =    @(x)2.*sin(2.*x)-3.*cos(x./2)

g=@(x)... 
    -1*(2.*sin(2.*x)-3.*cos(x./2));

%g =    @(x)-1*(2.*sin(2.*x)-3.*cos(x./2))

[x3,y5]=fminbnd(g,0,2*pi);

%x3 =   4.0968
%y3 =  -3.2647

[x2,y4]=fminbnd(f,0,2*pi);

%x2 =2.1864
%y2 =  -3.2647

y2=max(f(x));
y3=min(f(x));

plot(x,f(x));
set(gca,'XTick',[x2 x3]);
set(gca,'YTick',[y2 y3]);

(*after I paste this code here, it appeared not as nice as I had it in my program, don't know why)

+1  A: 

To create a vector with certain step do

x=0:0.001:2*pi;

Why do you have g(x) function and why are you using fminbind? Use MIN and MAX, return index of those values and find related x values.

[ymin, minindex] = min(f(x));
xmin = x(minindex);

For general case if you have multiple min/max values, index will contain only the first occurrence. Instead you can do:

minindex = find(y==ymin);

Or for real values to avoid precision error:

minindex = find(abs(y-ymin)<=eps);

Also your last statement returns error Values must be monotonically increasing. To avoid it sort your tick values.

set(gca,'XTick',sort([xmin xmax]));
set(gca,'YTick',sort([ymin ymax]));
yuk
Right, instead of this: set(gca,'YTick',sort([y2 y3])) .
Martin_87
it has to be this: set(gca,'YTick',sort([y3 y2]))
Martin_87
For `y` it's ok, but for `x` you don't know in advance the order of min/max.
yuk

related questions