1 / 54

MATrix LABoratory “MATLAB” TECNOLÓGICO DE MONTERREY CAMPUS SALTILLO

MATrix LABoratory “MATLAB” TECNOLÓGICO DE MONTERREY CAMPUS SALTILLO. Dr. Marco Iván Ramírez-Sosa Morán http ://www.geocities.com/mirsm/matlabprint.ppt. MATrix LABoratory MATLAB. PROGRAMACIÓN BÁSICA Y APLICACIONES. Contenido. Desktop de Matlab Command Window Workspace Command History

ban
Download Presentation

MATrix LABoratory “MATLAB” TECNOLÓGICO DE MONTERREY CAMPUS SALTILLO

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MATrixLABoratory“MATLAB”TECNOLÓGICO DE MONTERREY CAMPUS SALTILLO Dr. Marco Iván Ramírez-Sosa Morán http://www.geocities.com/mirsm/matlabprint.ppt CURSO DE MATLAB ITESM SALTILLO

  2. MATrixLABoratoryMATLAB PROGRAMACIÓN BÁSICA Y APLICACIONES CURSO DE MATLAB ITESM SALTILLO

  3. Contenido • Desktop de Matlab • Command Window • Workspace • Command History • Current Directory • Tipos de programación • Programación en el CW • Asignación de valores • Operaciones básicas con variables • Formatos de presentación • Iteraciones y bifurcaciones • Vectores • Gráficas 2D y 3D • Polinomios • Matrices • Imágenes RGB, JPG • Sistemas de ecuaciones • Funciones de transferencia • Matlab simbólico • Programación de archivos *.m • Del CommandHistory • Creación de Funciones • Programación en Simulink • Interacción Matlab-Simulink CURSO DE MATLAB ITESM SALTILLO

  4. Desktop de Matlab(Ventanas más importantes) • Command Window: • Donde se ejecutan las funciones y se realizan operaciones en forma de calculadora. Todo lo que se escribe en esta pantalla se graba en el Command History, y se pueden buscar operaciones anteriores con las flechas hacia arriba y abajo con la primera letra de la palabra a buscar). Se ponen comentarios con %. CURSO DE MATLAB ITESM SALTILLO

  5. Desktop de Matlab • Workspace: • Variables definidas (nombre, valor y tipo de dato) Se puede grabar, borrar y cargar variables guardadas. CURSO DE MATLAB ITESM SALTILLO

  6. Desktop de MatlabOtras ventanas • Command History: • Comandos y operaciones ejecutadas con anterioridad. La lista aparece separada por fechas automáticamente CURSO DE MATLAB ITESM SALTILLO

  7. Desktop de MatlabOtras ventanas • Current Directory: • Lugar donde se almacenarán archivos de datos, de programa y funciones creadas por usuario. (Se puede cambiar usando comandos de windows o usando los íconos en la misma ventana) CURSO DE MATLAB ITESM SALTILLO

  8. Tipos de Datos • Complex Double-Precision Matrices • Numeric Matrices • Logical Matrices • MATLAB Strings • Cell Arrays • Structures • Objects • Multidimensional Arrays • Empty Arrays CURSO DE MATLAB ITESM SALTILLO

  9. TIPOS DE PROGRAMACIÓN1. En el Command Window • Se asignan valores a variables de diferentes tipos, constantes, vectores, matrices, arreglos de caracteres, etc. >>A=34 >>B=[1 2 3;4 5 6] >>i='hola‘ >>m=['A34';'A25'] >>v=[1 2 3 4] >>Q=[1;2;3;4] >>r=3.14 >>E=1.23333e4 >>u=j >>I=9+8*j CURSO DE MATLAB ITESM SALTILLO

  10. Programación en el CommandWindow … • Se realizan operaciones con constantes ya definidas por default o por el usuario >>3*8 >>1/pi >>9-4 >>78*[3;5;2] >>78^2 >>1/eps >>[‘s’ ‘a’ ‘ltillo’] >>intmin >>realmax >>i/2 >>[2 3 4]+[8 9 10] CURSO DE MATLAB ITESM SALTILLO

  11. Programación en el CommandWindow … • Se evalúan funciones con argumentos definidos y los resultados se pueden asignar a variables o manejar en la variable ans >>sin(30) >>floor(3.5) >>3*exp(-6) >>x_1=factorial(6) >>y=tan(4)/abs(9+3*i)>>ans/3 >>var_num_4=5+[3 0 -5] CURSO DE MATLAB ITESM SALTILLO

  12. Programación en el CommandWindow … • Las asignaciones de variables se alamacenan en el Workspace y las de operaciones sin asignación se almacenan en la varibleans • Funciones de windows y propias de matlab que se pueden ejecutar desde la ventana de comandos: dircddeletecloseclearclcwhoswhowhat home whichisvarname CURSO DE MATLAB ITESM SALTILLO

  13. Programación en el CommandWindow … • Las variables almacenadas en el Workspace pueden ser grabadas en un archivo con el comando: >>saveNom_ArchNom_Var (sólo graba una) >>saveNom_Arch (graba todas) CURSO DE MATLAB ITESM SALTILLO

  14. Programación en el CommandWindow … • Las variables almacenadas en el Workspace pueden ser borradas con el comando: >>clearNom_Var (sólo borra una) >>clearall (borra todas) CURSO DE MATLAB ITESM SALTILLO

  15. Programación en el CommandWindow … • Las variables grabadas pueden recuperarse en cualquier momento con el comando: >>load Nom_Arch >> load C:\matlab71\work\Nom_Arch CURSO DE MATLAB ITESM SALTILLO

  16. Formatos de presentación • FORMAT SHORT • FORMAT LONG • FORMAT SHORT E • FORMAT LONG E • FORMAT SHORT G • FORMAT LONG G CURSO DE MATLAB ITESM SALTILLO

  17. Formatos de presentación … • FORMAT SHORT ENG • FORMAT LONG ENG • FORMAT HEX • FORMAT BANK • FORMAT RAT • FORMAT COMPACT • FORMAT LOOSE CURSO DE MATLAB ITESM SALTILLO

  18. Iteraciones y bifurcaciones: For & While >> for i=inicio:paso:fin ... %operaciones a iterar end >> >>while (condición) ... %operaciones a iterar end >> CURSO DE MATLAB ITESM SALTILLO

  19. Iteraciones y bifurcaciones: if & elseif >>if (condición 1) ..... elseif (condición 2) …. else (no se cumplen 1 y 2) … end >> CURSO DE MATLAB ITESM SALTILLO

  20. Iteraciones y bifurcaciones: Switch & case >>switch switch_expresion case case_expresion, … case {case_expr1, case_expr2,...} … otherwise …. end >> CURSO DE MATLAB ITESM SALTILLO

  21. Tipos de datosARREGLOS • Vectores (Arreglos unidimensionales) operaciones con vectores: normas, longitud, suma y producto, etc. >>v1=[1 2 3];%vector renglón >>v2=[1;2;3];%vector columna >>v3=3:.5:10;%vector con paso, inicio y fin >>v4=ones(1,4);%vector de unos >>v5=zeros(5,1);%vector de ceros CURSO DE MATLAB ITESM SALTILLO

  22. Vectores • Elementos de un vector, asignación y presentación Nom_vector(#reng or #col) >>v1(2) >>v2(3) >>v3(4:end) >>v3(1:3)=[.1 .3 .5] >>v3(1:2:end) >>m=find(v3==7) >>v3(m) >>[M i]=max(v3) >>n=length(v4) >>v4(n) >>v0(10)=3 >>v0(1:9)=rand CURSO DE MATLAB ITESM SALTILLO

  23. Vectores … • Operaciones con vectores: >>vt=v3’ %transpuesta de un vector >>d=norm(v3) %norma Euclideana >>v6=[1 2 3]/2+[5 6 7]-[4 0 2]*4+.5 >>v7=[3 5 6].*[1 -4 0] %prodHadamard >>v8=[2 4 8].^2 %potencia de cada elemento >>v9=[v6 v8 v7] >>d1=norm(v9) >>s=sum(v9) >>d1=sqrt(sum(v9.^2)) CURSO DE MATLAB ITESM SALTILLO

  24. Gráficas con Vectores • Graficar y1=sin(t)^2, t entre 0 y 10 seg >>t=0:.1:10; >>y1=(sin(t)).^2; >>plot(y1) >>plot(t,y1) >>plot(t,y1,’xr’) >>xlabel(‘tiempo s’),ylabel(‘voltaje v’) >>title(‘grafica de y_1 = (sin (t))^2’) CURSO DE MATLAB ITESM SALTILLO

  25. Gráficas con Vectores • Cerrar y abrir figuras >>figure(1) >>close >>figure(2),figure(5) >>close all • Empalmar figuras >>figure(1) >>y2=3*sin(0:.1:10);y3=sin(0:.1:10); >>plot(y2,’r*’);hold on;plot(y3,’om’); >> grid,axis([0 100 -4 4]),hold off CURSO DE MATLAB ITESM SALTILLO

  26. Gráficas con Vectores • Gráficas 3D >>x=[-2:.1:2]; >>y=[-2:.1:2]; >>z1=sin(x).^2+cos(y).^2; >>z2=cos(x).^2+sin(y).^2; >>plot3(x,y,z1) >>hold on,plot3(x,y,z2) >>grid CURSO DE MATLAB ITESM SALTILLO

  27. Gráficas 3D • Mallas de datos >> [xm ym]=meshgrid(x,y); >> z2=cos(xm).^2+sin(ym).^2; >> mesh(xm,ym,z2) >> figure,surf(xm,ym,z2) >> figure,meshc(xm,ym,z2) >> figure,meshz(xm,ym,z2) CURSO DE MATLAB ITESM SALTILLO

  28. Gráficas con Vectores • Polígonos: >>x=[0 0 1 1 0];y=[0 1 1 0 0]; >>plot(x,y),axis([-3 4 -3 4]),hold on, plot(x,y,'or') • Mover polígonos: >>x1=x+1.5;plot(x1,y),y1=y-1.5;plot(x1,y1) CURSO DE MATLAB ITESM SALTILLO

  29. Gráficas con Vectores • Escalamiento y movimiento de polígonos: >>closeall,clearall >> x=[0 0 1 1 0];y=[0 1 1 0 0]; >>for i=0:.1:5 x1=x*i+i;y1=y*i+i*i plot(x1,y1),holdon axis([-3 25 -3 25]) end >> CURSO DE MATLAB ITESM SALTILLO

  30. Rotación de vectores • Rotación a la derecha >>vector=[1:10] >>vector=[vector(2:end) vector(1)] • Rotación a la izquierda >>vector2=1:10 >>vector2=[vector2(end) vector2(1:end-1)] CURSO DE MATLAB ITESM SALTILLO

  31. Vectores como polinomios • Polinomio p(x) = 7x^4+5x^2-4x+3 se representa en Matlab: >>p=[7 0 5 -4 3]; • Raíces del polinomio: >>r=roots(p) • Evaluación del polinomio: >>pval_1=polyval(p,-3) >>pval_2=polyval(p,r(1)) CURSO DE MATLAB ITESM SALTILLO

  32. Polinomios • Producto de Polinomios >>p1=[1 0 1],p2=[1 -2 3] >>p3=conv(p1,p2) • Creación de polinomios con base en sus raíces >>p4=poly([1 1 1]) >>p5=poly([-1 -1 2 0]) >>p6=conv(p4,p5) >>raices=roots(p6) >>[factor,res]=deconv(p6,p4) %factorización CURSO DE MATLAB ITESM SALTILLO

  33. Polinomios • Fracciones de polinomios >>num=[1 2 3]; >>den=[1 -4 5 -7]; >>f=tf(num,den) • Fracciones parciales >>[res, polos, kte]=residue(num,den) >>[num1, num2]=residue(res,polos,kte) CURSO DE MATLAB ITESM SALTILLO

  34. Polinomios • Derivada de polinomios >>p = [1 0 -2 -5] >>q = polyder(p) CURSO DE MATLAB ITESM SALTILLO

  35. Curvas de mínimos cuadrados • Valores de entrada x, salida y >>x = [1 2 3 4 5]; y=[5.5 43.1 128 290.7 498.4]; >>p=polyfit(x,y,1); %1 es el grado del polinomio >>x2 = 1:.1:5; >>y2 = polyval(p,x2); >>plot(x,y,'o',x2,y2) >>grid on CURSO DE MATLAB ITESM SALTILLO

  36. MatricesArreglos n-dimensionales • Definición matriz nxm (n=reng,m=col) >>M1=[1 2 3 4 5;0 9 8 -1 2] %n=2,m=5 >>M2=ones(3,4) >>M3=zeros(2,3) >>M4=eye(4) >>M5=rand(5,2) >>M=pascal(5) >>M=magic(5) CURSO DE MATLAB ITESM SALTILLO

  37. Tamaño, elementos y operaciones >>s=size(M1) >>n=s(1) >>m=s(2) >>M5(3,1) >>M6(3,5)=-1 >>M6(4,7)=pi >>M7=eye(size(M5)) >>M7+2*M5 >>M6(1,:) >>M6(:,1) >>M6(2,1:3) >>M6(4,1:2:7) CURSO DE MATLAB ITESM SALTILLO

  38. Potencias de matrices >>B=A^2 %B=A*A >>C=A.^2 %element wise >>R=sqrt(A) %element wise >>R.^2 %A= R.^2 >>Q=sqrtm(A) >>Q^2 %A=Q*Q >>exp(A) %element wise >>D=expm(A) %A=logm(D) CURSO DE MATLAB ITESM SALTILLO

  39. Matrices • Producto punto >>v=[1 2 3] >>w=[4 6 8] >>M1=v*w’ %producto punto M1 n=1,m=1 • Producto de vectores y matrices >>M2=v’*w %producto M2 n=3, m=3 >>M3=[1 0 2;0 1 -1];M4=[1 3;7 8;9 0]; >>M=M3*M4 % n=? m=? >>M=M4*M3 %???????? CURSO DE MATLAB ITESM SALTILLO

  40. Imágenes >>I=imread(‘c:/trayectoria/archivo.jpg’); >> imshow(I) >> R(:,:,1)=I(:,:,1);R(:,:,2:3)=0; >> figure,imshow(R) >> G(:,:,2)=I(:,:,2);G(:,:,1:2:3)=0; >> figure,imshow(G) >> B(:,:,3)=I(:,:,3);B(:,:,1:2)=0; >> figure,imshow(B) CURSO DE MATLAB ITESM SALTILLO

  41. Matrices • Sistemas de ecuaciones x1= 3 a + 2 b x2 = - 4 a + 8 b Evaluación con valores a y b conocidos: >>a=-1;b=3; >>x=[3*a+2*b,-4*a+8*b] >>x=[3 2;-4 8]*[a;b] CURSO DE MATLAB ITESM SALTILLO

  42. Solución de sistemas de ecuaciones • Solución x1= 3 a + 2 b x2 = - 4 a + 8 b Dados x1 y x2 encontrar a y b: >>x=[4; -1]; >>M=[3 2;-4 8]; >>d=det(M) % d diferente de 0? >>sol=inv(M)*x;a=sol(1),b=sol(2) %existe? CURSO DE MATLAB ITESM SALTILLO

  43. Pseudoinversa • Solución del sistema sobredeterminado: x1 = 3b + 4c x2 = -5b +2c x3 = b – 3c Dados x1, x2, x3 encontrar b y c >>x=[-1 0 4]’ >>M=[3 4;-5 2;1 -3]; >>sol=pinv(M)*x >>sol=M\x >>xapp=M*sol >>norm(x-xapp) CURSO DE MATLAB ITESM SALTILLO

  44. Solución de sistemas de ecuaciones • Solución con a y b desconocidos x1 = 3 a + 2 b x2 = - 6 a - 4 b • Dados x1 y x2 encontrar a y b: >>x=[4 -1]’; >>M=[3 2;-6 -4]; %existe solución? >>x=[1 -2]’; >>solucion=???? %rank(M)==rank([M x]) inf CURSO DE MATLAB ITESM SALTILLO

  45. Eigenvalores, Eigenvectores y Factorización de matrices • Polinomio característico de una matriz p(s) = det ( s I – A ) eigenvalores = {roots[p(s)]} >>A=rand(4,4); >>p=poly(A) >>r=roots(p) >>[V L]=eig(A) >>[K,J]=jordan(A) >>K*J*inv(K) >>[U S]=schur(A) >>U*A*U’ >>[U S V]=svd(A) >>U*S*V’ CURSO DE MATLAB ITESM SALTILLO

  46. SYMBOLIC >>sym a b k t s % def variables simbol >>a+a+b+b+b >>a*a*a >>x=laplace(sin(t)) >>y=ilaplace(1/s) CURSO DE MATLAB ITESM SALTILLO

  47. TIPOS DE PROGRAMACIÓN2. Creación archivos *.m • Archivos .m de listado de comandos y de funciones: • Programas de ejecución de comandos, lectura y grabación de datos con inicio: closeall, clearall, clc, sólo usa variables globales. • Programación de una Función: fuction() • Ejecución de una función desde un archivo *.m (usa variables locales y globales) CURSO DE MATLAB ITESM SALTILLO

  48. Archivos *.m • Entrada y salida de datos de un archivo *.m c=input(‘Dame un dato numérico’); s=input(‘Dame un string’,’s’); disp([‘el dato numérico es ’ num2str(c)]) disp([‘el dato string es ’ s]) eval([s ‘_1=’ num2str(c)]) CURSO DE MATLAB ITESM SALTILLO

  49. EJERCICIO 1 • Hacer un programa que grafique un paraboloide usando programación en el CW y en un archivo *.m CURSO DE MATLAB ITESM SALTILLO

  50. Creación de unafunción • Definición dentro de un archivo *.m function [salida1,salida2,…] = nombre_funcion(arg1,arg2,…); … salida1=… salida2=… CURSO DE MATLAB ITESM SALTILLO

More Related