% Script 1 for Week 2 % More graphing possibilities for reports of various kinds. x = [1,3,0.5,2.5]; pie3(x) explode = [0,200,0,0]; figure(88) pie3(x,explode) % Follow the pie3 command with the following to label the slices. labels = {'Taxes','Expenses','Profit','Bribes',}; pie3(x,labels) pie3(x,explode,labels) % Here are some more graphing options. stem([1 2 4 5 5 6 9]) stairs([1 2 4 5 5 6 9]) a=[1 2 4 5 5 6 9]; b= [4 5 2 2 4 8 0]; scatter(a,b,200,'filled') xlim([min(a)-2 max(a)+2]) ylim([min(b)-2 max(b)+2]) % The following creates a polygon with vertices(1,5) and (2,6) and (2,3) and finally (1.5,7) and fills the area between with green. The last point is joined to the first by a straight line. fill([1 2 2 1.5], [5 6 3 7], 'g') % The next code does the same thing but with 126 vertices. x = 0:0.1:2*pi; fill( [ x fliplr(x) ] , [ sin(x) fliplr(sin(2*x)) ] ,'r') % various games with polar coordinates theta = 0:0.01:2*pi; rho = sin(2*theta).*cos(2*theta); x=rho.*cos(theta); y=rho.*sin(theta); figure(77) plot(x,y) figure(99) plot3(theta,x,y) figure(102) ezpolar('1+cos(t)') phi=@(theta) sin(2*theta).*cos(2*theta); figure(19) ezpolar(@(t)phi(t)) f=@(t) phi(t).*[cos(t),sin(t)] figure(42) fplot(f,[0,2*pi]) % fplot3 and polarplot are useful too! t=linspace(0,5); y=sin(t); tq=0:.4:5; yq=sin(tq); aq=cos(tq); plot(t,y) hold on plot(tq,yq,'go') quiver(tq,yq,ones(1,length(tq)),aq,.4) hold off % Now we create the function values of a function of two variables on grid of points in the plane and make a 3-d plot. X=linspace(-10,10); Y=linspace(-5,15); for i=1:length(X) for j=1:length(Y) Z(i,j)=sin(X(i))+cos(Y(j))+3; end end surf(X,Y,Z) % I really like surfc. surfc(X,Y,Z) shading interp meshc(X,Y,Z) % More on finite precision arithmetic: MATLAB does not understand that two numbers are different if they differ by less than the eps of the bigger number. The difference of the two will be a random (to us) value smaller than the eps of the bigger number. Its specific value is meaningless. Watch out! Infinity - Infinity can be anything! Also Micro/Micro can be anything if 1/Micro is near 10^309! eps(10^300) eps(10^(-300)) 7406/(3*10^(-324)) Inf>10 Inf+1000 10^309 10^308 10^308-(10^308-76) isinf(10^309) isfinite(10^309) 10^(-324) 10^(-324)==0 10^(-323) 10^(-323)==0 1/0 10^309-10^309 % NaN means Not a Number 0/0 isnan(0/0) NaN>5,NaN<5,NaN==5 isfinite(0/0) % In the following we explore further how to solicit user input and also print results in an attractive format. n=input(' type a number ') fprintf('The velocity is %8.4f m/s\n', n) % Look up help fprintf if you want more detailed info about formatting but here are some examples. x = [14328312 2 3 4 5]; y1 = [20.4 12.6 17.8 88.7 120.4]; y2=[20.44467 12.63321 170988.8 88.72222 120.4]; z = [x ;y1 ;y2] fprintf(' x y1\n'); % This does not print the values of the table we want. The quote marks mean what is inside is to be interpreted literally as the latin letters x and y, not as the numerical values the variables with those names contain. This is a problem when we want to mix text and variable values! fprintf('%5d %10.3f %.5f\n\n',z); % This sort of does the job but doesn't look nice, so we tweak it. fprintf('\n %9d %10.3f %15.5f\n\n',z); % If you want headers, create them. Note the curly bracket for the cell array "headers" and the cell array entry identification! We are creating a 1 by 4 cell array. Unlike matrices which they resemble in many ways, cell arrays can contain anything (strings, numbers, matrices, other cell arrays etc.) as their entries. headers={'eee' 'bbb' 'ccc' 'ddd'} size(headers) fprintf('\n\n\t\t %8s %9s %14s\n', headers{1},headers{2},headers{3});fprintf('\n \t\t %9d %10.3f %15.5f\n',z); % When you have it looking like you want you can take a screenshot of a part of the command window to import into your report. % You can create a cell array (which can have any number of dimensions) using a command like: Dog=cell(3,2) % This creates a two-dimensional three by two cell array with empty entries. You then populate the cell array with values any way you like. Note the difference between curly and round brackets. You identify locations in a cell array by curly brackets. Strings and matrices use round brackets. Dog{1,1}={'My' 'name' 'is' 'Larry' '.'};Dog{1,2}=18; Dog{2,1}='Hello';Dog{2,2}=[6;7];Dog{3,1}=55;Dog{3,2}=[4,6;8,9]; Dog{1,2}*Dog{3,2}*Dog{2,2} Dog{1,1} Dog{1,1}{2} Dog{1,1}{2}(3) celldisp(Dog) cellplot(Dog, 'legend') % Here is another way to create nice output following the MATLAB help webpage at % https://www.mathworks.com/help/matlab/ref/table.html LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'}; Age = [38;43;38;40;49]; Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80]; T = table(Age,Height,Weight,BloodPressure,'RowNames',LastName) % The Cell Array after the keyword 'RowNames' apparently has to have unique (not duplicated) string values and the columns have the names you give to the variables. % If you want to specify the column names directly with the columns given as vectors you can do it by using the keyword 'VariableNames' followed by .... well, the variable names as a cell array. T = table(categorical({'M';'F';'M'}),[45;32;34],... {'NY';'CA';'MA'},logical([1;0;0]),... 'VariableNames',{'Gender' 'Age' 'State' 'Vote'}) % The following is a loop with an exit test using break. I didn't talk about break in the earlier discussion of loops. In the line % if x < 0, break, end % if/when the condition is satisfied you immediately exit the outer (while) loop. x=8 while x > 0 x = x - 3; if x < 0, break, end disp(x) end % The following is an illustration of the pause command: it waits for any keystroke before executing the next step. This is useful for debugging code, walking through a loop step-by-step and following the variable values in the workspace, among other things. for n = 3:10 mesh(magic(n)) pause end % Sometimes your commands will spread over multiple lines and for readability reasons you might want to break these lines up. Do it with 3 dots. f3=@(t)... t.*... (t+1).*... 2 % Here is the function-plot command fplot(f3,[0 12]) % or, quick and dirty, fplot(@(t) t.*(t+1).*2, [0 12]) Sources and types of errors: blunders (such as model errors) truncation errors roundoff errors measurement errors true error = true value - approximation In real problems you never actually know the true error so we can use approximate error = present approx - previous approx If this is small it means the approximation procedure you are using is "slowing down" and may be (often will be) converging on a true solution. more important than approx error in understanding the approximation process is: relative approximate error = (present approx - previous approx)/present approx "Small" alone doesn't usually matter. "Small in proportion to where you are going" is usually the important thing. The RAE (relative approximate error) ATTEMPTS to gauge this. Very often you run a MATLAB script until the RAE is smaller than a preset value and then call it good (enough): i.e. end the approximation. Frequently scripts stop based on PERCENT relative approximate error, i.e. 100 times the relative approximate error. You have to look carefully in the script to see which you are dealing with. Here is a warning example: The harmonic series S_n, the sum as i goes from 1 to n of 1/i, diverges. Even though the terms you are adding on become minuscule they don't get small fast enough. There are 2^k terms from i=2^k+1 to i=2^(k+1) and the sum of those terms is a number between 1/2 and 1. Since there is no limit to how big k can be, you keep adding additional "more-than-one-halfs" .... forever. Divergence. What do you suppose the RAE (S_(n+1)-S_n)/S_n looks like for n=10^12? Does the harmonic series converge on a machine which uses finite precision arithmetic? % A list of built-in functions help elfun % games with strings x='eke' x=1*x x=char(x) y=x+[1,2,3] y=char(y) % games with matrices c=[3 5 7;2 5 1;8 9 3] [ [1 4 5] [5 7 9] [2 5 7] ] [ [1 4 5] ,[5 7 9] ,[2 5 7] ] [ [1 4 5]'; [5 7 9]' ;[2 5 7]' ] b=[ [1 4 5]' [5 7 9]' [2 5 7]' ] % b^(-1) and inv(b) return the inverse matrix. b^(-1) a=inv(b) % games with "point arithmetic" a*b a.*b a^2 a.^2 b/b % b/b is roughly (in this case it IS) b*inv(b) b./b d=[1;3;7] % a\b is roughly (in this case it IS) inv(a)*b a\b inv(a)*b % But what is going on in the next line? a\d size(a) q=size(a) [a,b] length(ans) eye(size(a)) ones(size(a)) a-9 a-9*ones(size(a)) zeros(size(a)) rand(4,3) randi(25,size([a,b])) % fun with complex numbers clear i j i^2 j^2 % games with loops for i=1:10^12 k=i+1 end % On a Mac hit "command period" to break and return to the command prompt. On a PC Ctrl+C or Ctrl+Break works. i^2 % oops. I hope this doesn't interfere with any complex arithmetic you might be doing elsewhere! Beware of this!! clear i^2