% A few Matlab examples including 2D and 3D graphics, animations, and % matrix operations. set(0,'DefaultTextInterpreter','LaTeX') %% 2d plot clear, clf x=-1:.1:1; y=x.^3; plot(x,y) box off xlabel('$x$') ylabel('$y$') title('$y=x^3$') %% 3d plot clear, clf [x y]=meshgrid(linspace(-1,1,50)); z=x.^2+y.^2; mesh(x,y,z) %% 3d plot (improvement 1) clear, clf r=linspace(0,1,25); vth=linspace(0,2*pi,25); [r vth]=meshgrid(r,vth); x=r.*cos(vth); y=r.*sin(vth); z=r.^2; mesh(x,y,z) %% 3d plot (improvement 2) clear, clf axes('Pos',[.2 .1 .6 .8]) r=linspace(0,1,25); vth=linspace(0,2*pi,25); [r vth]=meshgrid(r,vth); x=r.*cos(vth); y=r.*sin(vth); z=r.^2; surfl(x,y,z+.5), hold on shading interp, colormap copper contour(x,y,z), hold off set(gca,... 'XLim',[-1 1],... 'YLim',[-1 1],... 'ZLim',[-inf inf],'ZTickL',[0:.5:1.5],'ZTickL',[-.5:.5:1],... 'Box','on','Color',[1 1 1]) grid off title('$z=x^2+y^2$') xlabel('$x$') ylabel('$y$') zlabel('$z$') %% movie clear, clf mov=avifile('example.avi') x=linspace(-3,3,25); y=linspace(-3,3,25); [X Y]=meshgrid(x,y); z=peaks(X,Y); surf(x,y,z) shading interp axis([-3 3 -3 3 -8 8]) set(gca,'Visible','off') N=25; for I=1:N surf(x,y,sin(2*pi*I/N)*z) shading interp axis([-3 3 -3 3 -8 8]) set(gca,'Visible','off') mov=addframe(mov,getframe(gca)); end mov=close(mov); %% matrix multiplication clear N=100; rand('state',1), A=ceil(5*rand(N)); rand('state',2), B=ceil(5*rand(N)); C=zeros(N); tic for I=1:N for J=1:N dmy=0; for K=1:N dmy=dmy+A(I,K)*B(K,J); end C(I,J)=dmy; end end toc tic, C=A*B; toc %% determinants, eigenvalues, etc. clear A=[1 0;0 5]; det(A) [V D]=eig(A) A*V D*V %% fourier series clear, clf t=linspace(-.5,.5,250); f=.5*(square(t+.25)-square(t-.25)); h=[]; h=plot(t,f,'r','LineW',1); hold on n=1:15; A=[.5 sin(n*pi/2)./(n*pi/2)]; fn=A*cos(2*[0 n]'*pi*t); h=[h plot(t,fn,'b','LineW',.5)]; hold off set(gca,... 'XLim',[-.5 .5],'XTick',[-.5 0 .5],... 'YLim',[-.5 1.5],... 'Box','off') legend(h,{'$f(t)$',['$f_{' num2str(max(n)) '}(t)$']}) xlabel('$t$') set(0,'DefaultTextInterpreter','TeX')