%% E5 Matlab Intro % Erik Cheever - Fall 2009 %% Simple math %% % addition 3+5 %% % multiplication 3*5 %% % sin() - note the argument is in radians sin(pi/4) %% % sind() - takes argument in degrees sind(45) %% % sqrt sqrt(3) %% % power 3^5 %% 3^0.5 %% 3^1/2 %% % natural log (ln) log(10) %% % log base 10 log10(10) %% % pi pi %% % show more digits format long pi %% % show fewer digits format short pi %% % scientific notation 256*256*256*256 %% Variables - not equivalent to mathematical notation % variables go on left side. Read equals sign as "gets": x gets 3 x=3 %% % display value of variable x %% % note that you can't switch order. % % 3=x gives an error %% % Whatever is on left gets a new value y=4 %% x=y %This changes the value of x %y=x would have changed value of y %% % anything following a "%" sign is a comment % % if you put a semicolon ";" at the end of a line, the result doesn't % display. x=5; %% % The above result wasn't displayed. But we can check the value of x x %% Matrices and vectors %% % Row vector a=[1 3 5 -1] %% % Column vector b=[2; 4; 1; 0] %% % Get 3rd element of each a(3) %% b(3) %% % Try to add %a+b %% % define another row vector c=[1 0 3 1] %% % now we can add a+c %% % Define a 2x2 (2 rows x 2 colums) matrix. A=[3 5; 6 -1] %% % Access individual elements A(2,1) % 2nd row, 1st column %% % Retrieve a whole column.... A(:,1) % 1st column %% % or a row... A(2,:) % 2nd row %% % Another matrix B=[3 5; 5 2] %% % Add matrices A+B %% % Multiplication A*B %% % Transpose (switch rows and columns)\ A A' %% % Find inverse inv(A) %% % check inverse ans*A %% % can also define identity matrix I=eye(2) %% % check A*I %% Creating a range of numbers, and plotting % range of numbers x=linspace(0,3*pi,12) %x is linearly spaced with 12 elements %% % calculate sin() y=sin(x) %% % plot plot(x,y) %% % Label the plot title('Sin(x) vs x'); xlabel('x values'); ylabel('sin(x)'); %% % use more points x=linspace(0,3*pi,1000); y=sin(x); plot(x,y,'r-.','LineWidth',2); %% % a circle (radius = 2) theta=linspace(0,6*pi,1000); x=2*cos(theta); y=2*sin(theta); plot(x,y,'r','LineWidth',2); %% % a spiral (radius=theta) x=theta.*cos(theta); y=theta.*sin(theta); plot(x,y,'r','LineWidth',2); %% % a 3-D spiral plot3(x,y,theta,'r','LineWidth',2); %% % Label the axes xlabel('x'); ylabel('y'); zlabel('theta'); title('3d Spiral'); %% Patch graphics %% % Define a "patch" clf; %clear the figure x=[0 1 1 0]; y=[0 0 1 1]; myPatch=patch(x,y,[1 0 0]); %(x, y, color) %% % Set axes axis([-5 5 -5 5]); %[xmin xmax ymin ymax] grid %% % move the patch set(myPatch,'Xdata',x+2); %% % change the color set(myPatch,'FaceColor',[0 0 1]); %% % a 3d patch x=[0 0; 1 1; 1 1]; y=[0 0; 1 -1; 0 0]; z=[0 0; 1 0.5; 0 0]; tcolor(1,1,1:3) = [1 0 0]; tcolor(1,2,1:3) = [0 1 0]; my3dPatch=patch(x,y,z,tcolor);