Assignment 4
x=linspace(-2*pi,2*pi,1001); y=abs(mod(x+pi,2*pi)-pi); N=5; a=[pi/2,zeros(1,2*N)]; a(2:2:end)=-(4/pi)*(1:2:(2*N)).^(-2); y_2N=part_sum_c(a,0,x); err=(2/pi)/(2*N-1); plot(x,y,'-.g',x,y+err,'-.r',x,y-err,'-.r',x,y_2N,'b')Script mfiles contain code that you want to run repeatedly or perhaps at different times, with minor modifications to either the code or some parameter. To make one, open Matlab. Either go to the toolbar and select file, new, mfile, or, in the command window, type this:
edit unif_ex_scriptThis brings up Matlab's built in editor. Type or copy the code above (no HTML tags, though!) in the file. Click save. The file
unif_ex_script.m
will be put in the directory that Matlab
is working in at the time. The file part_sum_c.m
must
either be in this directory, or in a directory included in Matlab's
path. Now, to run the code as is, go to the command window and type
the following:
unif_ex_scriptNote that you don't need the extension ".m" on the command line. To change the parameters, simply edit the file as you would normally do with text, save, and then run the code.
Function mfiles are similar to script mfiles. They behave more like true functions in that they take input arguments and provide some type of output, which could be numerical, graphical, or something else. For example, suppose we want the same plot as above, but that we want to input x and N. Again, bring up the Matlab editor:
edit unif_ex_functThis time, type the following code in the file.
function unif_ex_funct(x,N) y=abs(mod(x+pi,2*pi)-pi); a=[pi/2,zeros(1,2*N)]; a(2:2:end)=-(4/pi)*(1:2:(2*N)).^(-2); y_2N=part_sum_c(a,0,x); err=(2/pi)/(2*N-1); plot(x,y,'-.g',x,y+err,'-.r',x,y-err,'-.r',x,y_2N,'b')Click save. The mfile
unif_ex_funct.m
is a function that
takes two arguments, x and N, and outputs a graph. To run it, you must
first give x and N values, then run it. Here is how to do that
x=linspace(-4*pi,4*pi,2001); N=2; unif_ex_funct(x,N)If you want to now run the program with x the same and N=3, just type this
N=3; unif_ex_funct(x,N)or, since it already has x stored, you can directly change it in the function argument list,
unif_ex_funct(x,3)Names for mfiles must start with an alphabetic character. After that, it may contain any combination of alphanumeric characters and underscores - but not hyphens, periods, etc. Here are the Matlab exercises.