Week 6,ProgramsScripts,Why programs,a = rand(1000); s = 0; for i = 1:1000 s = s+a(i); end s/1000,When we want to do something repeatedly.Suppose we want to see if the average of 1,000 uniformly-distributed random numbers is close to 0.5.,Suppose we want to run this several times.,,In the “Command Window”Select the “File” menu commandSelect “New / M file”This should start the m-script Editor Window. Type your program into the window.,To create a Matlab program (.m file),,,,,Enter your program here,To save:,,,Select the menu command File/Save and give the program an appropriate name, e.g. testavg. The ‘.m’ should automatically be added to the program name. The file will be saved into your work space. (See the Current Directory Window.) Click back to the Command Window. You can check your program by the Matlab command dir *.m.,Type the name of the program without the ‘.m’ and hit “Enter”. E.g. testavgans= 0.4917The program runs and gives you the result. To run it again, just do the same: testavgIt will give you another average.,To Run:,,Have a Head:,Give some explanations and details of the programs operation Comment them by using % at the beginning of each comments.,Typing ‘help testavg’ will display this header.,,,% simple program called multiply.m % take two variables and multiply them a = 5 ; b = 3 ; product = a * b,Some Examples of M Scripts,Type this into your editor, save it with the name “multiply.m” and ‘run’ it with the command multiply,,The following program graph the function z=xp+yp. Enter the program and save as sketch.m[x, y] = meshgrid(-3:0.1:3, -3:0.1:3);z = x .ˆp + y .ˆp;mesh(x,y,z);Type p=2; sketch and p=4; sketchWhat will the shape be for p odd, and for p large?,To sketch a surface :,,Sometimes we want to change the results of the program by changing some of the variables.For example, we may want to compute the average of n numbers instead of 1,000 numbers where n is given by the users of the program.,Input the Arguments,First is to print them w
展开阅读全文