La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Programación Multimedia INTRODUCCIÓN A LA PROGRAMACIÓN EN MATLAB

Presentaciones similares


Presentación del tema: "Programación Multimedia INTRODUCCIÓN A LA PROGRAMACIÓN EN MATLAB"— Transcripción de la presentación:

1 Programación Multimedia INTRODUCCIÓN A LA PROGRAMACIÓN EN MATLAB
7- Noviembre INTRODUCCIÓN A LA PROGRAMACIÓN EN MATLAB Presentación Personal. ©Carlos A. Lázaro Carrascosa.

2 Programación Multimedia
Introducción a MatLab 7- Noviembre MATLAB: MATrix LABoratory Programa de simulación Ayuda potente Entorno de trabajo © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

3 Programación Multimedia
Introducción a MatLab 7- Noviembre Entorno de trabajo PATH BROWSER EDITOR Y DEBUGGER WORKSPACE BROWSER FORMATOS DE SALIDA © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

4 Programación Multimedia
Vectores y Matrices 7- Noviembre Generalidades No hace falta establecer su tamaño de antemano Definición: A=[1 2 3; 4 5 6; 7 8 9] Transposición: A’ Inversión: inv(A) Vector fila: A=[1 2 3] Vector columna A=[1;2;3] © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

5 Programación Multimedia
Vectores y Matrices 7- Noviembre Operaciones Suma (+) Resta (-) Multiplicación (*) Traspuesta (‘) Potenciación (^) Producto a nivel de elemento (.*) División a nivel de elemento (./) Resolución de sistemas lineales © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

6 Programación Multimedia
Vectores y Matrices 7- Noviembre Tipos base Reales Ej. 5.0 Complejos Ej j Cadenas de caracteres Ej. ‘cadena’ Acceso indexado © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

7 Programación Multimedia
Vectores y Matrices 7- Noviembre Matrices predefinidas eye(4) zeros(3,5) zeros(4) ones(2) linspace(x1,x2,n) rand(3) hilb(3) © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

8 Programación Multimedia
Funciones 7- Noviembre Devolución múltiple de valores Funciones sin argumentos no llevan paréntesis No son palabras reservadas del lenguaje Número de argumentos variable © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

9 Programación Multimedia
Funciones 7- Noviembre Argumentos: expresiones u otras llamadas Argumentos: pasados por valor Ejemplos (modo escalar): sin(x), cos(x), exp(x),abs(x)... Ejemplos (vectores): min(x), sum(x), mean(x)... Ejemplos (matrices): lu(A), det(A), qr(A), norm(A), norm(A,1)... © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

10 Programación Multimedia
Otras características 7- Noviembre Elementos adicionales Gráficos: Funciones plot(), pie(), ginput(), plot3(), surf()... Llamadas al sistema: Operador ! Comentarios: Operador % © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

11 Programación Multimedia
7- Noviembre Bifurcaciones y bucles: if, switch, for, while, break, try...catch...end Entrada / Salida: input, disp Definición de funciones: function[valores de retorno] = name(argumentos) Funciones: No hay return. Varios: estructuras, fopen(), fclose(), fprintf(), fscanf(), exportación, argumentos variables, creación de interfaces (guide)... © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

12 Programación Multimedia
Introducción 7- Noviembre Programa de computación numérica. Funciones incluidas + Toolboxes: data analysis, signal processing, optimization. Posee gran cantidad de funciones para gráficos 2-D y 3-D y animación. Ambiente similar a UNIX. Aparece un prompt para ingresar sentencias MatLab. Cuando se pulsa <ENTER> la sentencia se ejecuta y aparece un nuevo prompt. Si una sentencia culmina con punto y coma ( ; ), no se muestran resultados (sí se hacen los cálculos). Instructor notes: Matlab is part language and part environment. You can enter Matlab commands directly into the command window and Matlab will execute them as soon as the <ENTER> key is pressed. You can also write programs in Matlab which are a collection of Matlab commands and run those programs in the Matlab environment. This is much like writing a program in C or C++ and running it in the UNIX environment or the Visual Studio environment, for example. One of the functions of the semicolon in Matlab, depending on the immediate context, is that of output suppression operator. By placing a semicolon at the end of a line, the output generated by that line will not be displayed in the command window. The line will still be executed, but the results will not be displayed. This is particularly useful when producing large arrays of data that you don’t want displayed in the command window because of their size. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

13 Programación Multimedia
Comienzo 7- Noviembre Para comenzar, teclear alguno de los siguientes comandos: helpwin, helpdesk, or demo >> a=5; >> b=a/2 b = 2.5000 >> Instructor notes: This slide shows a quick example of using and not using the semicolon to suppress output to the command window. As you can see the output from a = 5 is suppressed, while the output from b = a/2 is not. It may be a good idea to mention that while suppressing output for a simple situation such as this is not really necessary, when large arrays are used it is very useful and prevents numerous lines of data from scrolling by. In addition it indicates one method of invoking Matlab’s help system. All three commands, helpwin, helpdesk, and demo, take you to essentially the same place in the help system. You can also invoke the helps system by using the mouse and clicking on Help:Matlab Help © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

14 Programación Multimedia
Nombres de Variables 7- Noviembre Los nombres SON case-sensitive. Pueden contener hasta 63 caracteres. Deben comenzar con una letra seguida de letras, dígitos o underscores (_). Instructor notes: Variable names in Matlab are case sensitive. As of Matlab version 6.5 variable names can contain up to 63 characters. The previous limit was 31. Variable names must start with a letter, but after that may be comprised of digits, underscores, and other letters. It is a good idea to make variable names descriptive of what they represent. In addition, it is a good idea not to use, as variable names, any of the default variables for which Matlab has already established values. In Matlab it is possible to use these default names, but the result will be that the default value stored in that variable will no longer be available until Matlab is stopped and restarted. So, if you redefine pi, for example as pi = 10, then the default value of pi would not be available until Matlab was stopped and restarted. It’s a good idea to avoid using variables that have the same names as the special variables, even though you are allowed to do it. It is also a good idea to avoid using variable names that are the same as Matlab built in functions, such as sum(), for example. Again, you are allowed to do it, but if you define a variable sum, then you will lose the built in function sum () until Matlab is stopped and restarted. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

15 Programación Multimedia
Variables Especiales 7- Noviembre ans Nombre por defecto de los resultados. pi Valor de  = … eps la menor distancia entre números float inf Infinito NaN No es un número, por ejemplo: 0/0 i ó j i = j = raíz cuadrada de -1 realmin El menor número real positivo utilizable. realmax El mayor número real positivo utilizable. Instructor notes: Here is a list of Matlab’s special variables. Probably the most common ones that would be inadvertently redefined would be i and j, particularly when used in a for loop. This will most often not be a problem unless you are also working with imaginary numbers. realmin is approximately 2 *10^(-308). realmax is approximately 1.8*10^(308), and eps is approximately 2 *10^(-16). This is the smallest difference that Matlab can distinguish between two numbers. You will get NaN when you do an operation that causes a divide by zero. You will get inf when you decide something very big by something very small. For example, realmax/realmin. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

16 Operadores y Asignación
Programación Multimedia Operadores y Asignación 7- Noviembre Potencia ^ or .^ a^b or a.^b Multiplicación * or .* a*b or a.*b División / or ./ a/b or a./b or \ or .\ b\a or b.\a OBSERVAR: /8 = 8\56 Suma a + b Resta a - b Asignación = a = b (asigna b a a) Instructor notes: Here we see Matlab’s mathematical and assignment operators. The carat is used for exponentiation, the asterisk for multiplication and the forward slash and backward slash for division. Note that the division operation is different depending on which way the slash “leans”. It’s helpful to remember that it always leans toward the number doing the dividing, or, depending on how you like to think about it, away from the number being divided. We also have the plus sign for addition, the minus sign for subtraction and the equals sign for assignment. It may be helpful to remind students that the equals sign is doing an assignment and not a comparison. There can never be more than one variable to the left of the equals sign. While it’s OK to have this in algebra, it does not work that way in the Matlab environment. You will note that an additional set of operators for exponentiation, multiplication, and division exist all of which are preceded by a decimal point. These are referred to as “dot operators”. They allow Matlab to do element by element computations, rather than following the rules of linear algebra, when the variables involved are vectors and matrices. If one or more of the pair of variables involved in an operation is a scalar, then the dot and normal operators will work the same. However, if both elements of a pair of variables are vectors or matrices of the same size, then the dot operators must be used in order to perform element by element math rather than strict linear algebra. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

17 Programación Multimedia
Otros símbolos 7- Noviembre >> prompt ... Continúa la sentencia en la línea siguiente , Separa sentencias y datos % Comentarios ; (1) elimina la salida (2) separador de filas en una matriz : rango Instructor notes: Two greater than signs are the prompt in Matlab’s command window. If you’re entering a line or equation that is longer than the available space in the window, then an ellipsis (three dots) can be used to continue that line on to the next line. A comma is used to separate individual statements or data. For example, when entering elements in a vector, you can use a comma to separate elements of the vector. The percent sign indicates that everything that follows it until the end of the line is a comment. It is particularly useful when writing programs in Matlab or when you want to include information like name, problem number, seat number, etc. in the command window prior to printing. The semicolon has two functions. At the end of a line, it suppresses output. Very useful when the variables involved are large vectors or matrices. It also acts as a row separator when entering elements of a matrix. The semicolon indicates the end of one row and the beginning of the next. The colon is used for specifying sub-parts of a matrix, for example when wanting to extract two columns from a matrix of several columns More of these two will be seen in later slides. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

18 Programación Multimedia
Matrices 7- Noviembre MATLAB trata a todas las variables como matrices. Los Vectores son matrices con sólo una fila O una columna. Los Escalares son matrices con una fila Y una columna. Instructor notes: All variables in Matlab are matrices. Vectors are special matrices that have either one row or one column. Scalars are special matrices that have only one row and one column. A variable’s dimension can easily be changed just by redefining its elements or by assigning a variable of different dimensions to it. It’s important to note that a variable’s dimensions can change at any point during a Matlab session as needed. However, they cannot change on the fly within a given equation. For example if the 2x3 matrix m1 were added to the 3x2 matrix m2, Matlab would give an error indicating that the dimensions did not match correctly. Matlab would not automatically alter the dimension of one of the matrices so that the two could be correctly added together. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

19 Programación Multimedia
Escalares 7- Noviembre Un escalar puede crearse en MATLAB como sigue: >> a_value=23 a_value = 23 Instructor notes: A scalar is a specialized matrix with one row and one column. One way to create a scalar in Matlab is simply to assign a value to a variable. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

20 Programación Multimedia
Vectores 7- Noviembre Una matriz con sólo una fila se llama vector: >> rowvec = [12 , 14 , 63] rowvec = Instructor notes: A matrix with a single row is called a row vector. Row vectors in Matlab can be created by assigning a variable to a list of individual elements. The elements must be contained within square brackets and can be separated by commas or spaces or both. Matlab is not overly picky about the separators between elements of a given row vector or row within a matrix. To reemphasize the semicolon as output suppression operator, you might want to point out that putting a semicolon at the end of the line assigning elements to rowvec would have prevented its contents from being displayed. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

21 Programación Multimedia
Vectores columna 7- Noviembre Una matriz con sólo una columna se llama vector columna (observar los punto y comas): >> colvec = [13 ; 45 ; -2] colvec = 13 45 -2 Instructor notes: A matrix with a single column is called a column vector. Column vectors in Matlab can be created by assigning a variable to a list of individual elements. The elements must be contained within square brackets and can be separated by semicolons or <ENTER>s or both. Matlab is not overly picky about the separators between elements of a given column vector or column within a matrix. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

22 Programación Multimedia
Matrices 7- Noviembre Una matriz se crea de la siguiente manera (observar las comas y los “punto y coma”). Las comas pueden reemplazarse por espacios. >> matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9] matrix = Instructor notes: Creating a matrix in Matlab is essentially a combination of creating row vectors and column vectors. Inside of square brackets the elements of a given row are separated by commas or spaces and the rows are separated from each other by semicolons or <ENTER>s. Thus, in this example we see rows with three elements each separated by semicolons. It is important to note that each row must have the same number of elements, otherwise Matlab will give an error message. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

23 Extracción de una Sub-Matriz
Programación Multimedia Extracción de una Sub-Matriz 7- Noviembre Una parte de una matriz puede extraerse y almacenarse como una matriz más pequeña. La sintaxis es: submatriz = matriz(r1:r2, c1:c2); r1 : r2 desde fila r1 hasta fila r2 c1 : c2 desde columna c1 hasta columna c2 Instructor notes: Now we get to see the colon, or array addressing operator, in action. This operator allows us to extract a sub-matrix from another matrix. You can imagine this being particularly useful when you have a matrix that contains a column of sampling times and multiple columns of data. You can easily extract the time column and a data column for further analysis or graphing. A submatrix is extracted by using the original matrixe’s name followed, in parentheses, by the beginning row you want extracted separated by a colon from the ending row you wanted extracted. Next comes a comma to separate the rows from the columns. And then, the beginning column you want extracted separated by a colon from the ending row you want extracted. If r1 equals r2 then only one row will be extracted. Likewise, if c1 equals c2, then only one column will be extracted. So, if r1 equals r2 AND c1 equals c2, the result will be a scalar. There are some shortcut notations. If you include the colon, but no r1 and r2 or c1 and c2, then you will get all of the elements of the row or column, respectively. If matrix were followed by two colons separated by a comma within parentheses, then in this example sub_matrix would be identical to matrix. If you specify just a single row or single column with no colon to specify a range of rows or columns, then you will get only that specific row and/or column. If you specify a row or column that is outside of the allowable range of rows or columns, Matlab will give you an error message. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

24 Programación Multimedia
Otras Sub-Matrices 7- Noviembre Extracción de un vector columna de una matriz. Primero la creamos: >> matriz = [1,2,3; 4,5,6; 7,8,9] matriz = Y ahora extraemos la columna 2 de la matriz recién creada: >> col_2 = matriz(:,2) col_2 = 2 5 8 Instructor notes: Now some extraction examples. First the matrix is set up. It might be good to reemphasize that those commas could just as well be spaces and the semicolons could be replaced by <ENTER>s. The result would be the same. In the second panel the second column is extracted. The colon with no rows indicated means all rows will be extracted, and the 2 with no colon and ending row indicates that only the second column is extracted. This could also have been written col_two = matrix(1:3, 2:2) or matrix(:, 2:2). It might be good to point this out so that students are comfortable with the strict way of writing it before trying to use the shortcut method. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

25 Programación Multimedia
Otras Sub-Matrices 7- Noviembre Extracción de un vector columna de una matriz. Primero la creamos: >> matriz = [1,2,3; 4,5,6; 7,8,9] matriz = Y ahora extraemos la fila 2 de la matriz recién creada: >> fil = matrix(2:2 , 1:3) fil = Instructor notes: Now some extraction examples. First the matrix is set up. It might be good to reemphasize that those commas could just as well be spaces and the semicolons could be replaced by <ENTER>s. The result would be the same. In the second panel the second column is extracted. The colon with no rows indicated means all rows will be extracted, and the 2 with no colon and ending row indicates that only the second column is extracted. This could also have been written col_two = matrix(1:3, 2:2) or matrix(:, 2:2). It might be good to point this out so that students are comfortable with the strict way of writing it before trying to use the shortcut method. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

26 Lectura de Datos desde Archivos
Programación Multimedia Lectura de Datos desde Archivos 7- Noviembre MATLAB lee el archivo completo y almacena todos sus datos en una matriz: >> load mydata.dat; % loads file into matrix. % The matrix may be a scalar, a vector, or a % matrix with multiple rows and columns. The % matrix will be named mydata. >> size (mydata) % size will return the number % of rows and number of % columns in the matrix >> length (myvector) % length will return the % total no. of elements in % myvector Instructor notes: The load function is convenient for reading into Matlab the entire contents of a file and storing the contents in a matrix all in one command. The matrix created to store the data will have the same name as the file, minus any extension on the file. There are a decent number of options that accompany the load command which you can read about using >> help load. It’s important that the file being loaded either be in the same directory in which Matlab is currently working, or that the directory where the file is stored be in Matlab’s search path, or that the necessary pathname be included along with the file name when invoking the load command. The size function returns the number of rows and columns in a matrix. Again, there are other options that you can see using >> help size, but the most important thing is that size returns the number of rows and columns in a matrix. The length function returns the number of elements in a vector. It’s interesting to note that length will also work on a matrix and will return the greater of the row length or the column length. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

27 Programación Multimedia
Gráficos con MATLAB 7- Noviembre MATLAB grafica un vector versus otro. El primero será la abscisa (x) y el segundo la ordenada (y). Deben tener la misma longitud. MATLAB también grafica un vector versus su propio índice, el que será la abscisa (x). Dados dos vectores, “time” y “dist” : >> plot (time, dist) % plotting versus time >> plot (dist) % plotting versus index Instructor notes: Matlab’s plotting capabilities are one of its most powerful and convenient features. Typically the plot () command takes two arguments with the first being the abscissa and the second being the ordinate. The vectors must be of the same length. If only one argument is provided, then Matlab treats that argument as the ordinate and uses the index of each element of the vector as the abscissa. The plot () command is fairly flexible. It is probably a good idea to have students in the mode of doing >> help plot so that they can see the other options that are available with plot (). For example, you can control the type of line or data point being displayed as well as its color. Most generally the plot () command is written as plot (x1, y1, s1, x2, y2, s2, ...) where the x’s are abscissa vectors, the y’s are ordinate vectors, and the s’s are strings contained within single quotes that specify the plotting options for the preceding (x, y) vector pair. When plot () is used with multiple sets of arguments, a single plot window is opened and all of the data are displayed on the same plot. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

28 Programación Multimedia
Gráficos con MATLAB 7- Noviembre Hay muchos comandos totalmente configurable para agregar anotaciones (“annotations”) a los gráficos, etiquetas de ejes, título, leyendas… >> % To put a label on the axes we would use: >> xlabel ('X-axis label') >> ylabel ('Y-axis label') >> % To put a title on the plot, we would use: >> title ('Title of my plot') Instructor notes: As would be expected, there are commands for putting axis labels and titles and legends and text on plots. For the most part, these commands take as an argument a string. The legend () command has a numbered list of positions on the page that can be an additional argument. Use >> help legend to see a list of these. This can be done via the command line as the slide indicates or they can be done interactively from the plot window. So, a student could quickly plot the data, if desired, and then using the icons once the plot window has opened he or she could add the desired title, legend, labels, etc. It is probably most useful to become comfortable using the command line commands, but other options do exist. Again it would be good to point out the >> help plot because doing so will return the names of the plot annotating commands. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

29 Programación Multimedia
Gráficos con MATLAB 7- Noviembre Cómo graficar una columna versus otra: >> first_vector = mydata(:, 1); % Primera columna >> second_vector = mydata(:, 2); % Segunda columna >> % y ahora graficamos >> plot(first_vector, second_vector) Instructor notes: As we have seen, vectors can be extracted from matrices. If we had a matrix with two columns of data in it, we could extract two vectors of data from the matrix, in this case column vectors, and then use the plot () command to plot the data. Note that it’s not necessary to create the two vectors. mydata(:,1) could be used as the first argument to plot and mydata(:,2) could be used as the second argument, if desired. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

30 Programación Multimedia
Otros comandos útiles 7- Noviembre who Listado de variables whos Listado de variables con su tamaño. help Ej.: >> help sqrt (Ayuda sobre sqrt) lookfor Ej.: >> lookfor sqrt Busca la palabra sqrt en m-files what Ex:>> what a: Listado de archivos MATLAB en a: clear Borra TODAS las variables del workspace clear x y Borra las variables x e y del workspace clc Borra la ventana de comandos Instructor notes: The next two slides list some useful commands. Who will return the names of all the variables currently in the Matlab workspace. Whos will provide the same information as well as the amount of storage set aside for each variable...that is, their size. The help command is very useful and will return help information on how to use any of the built in Matlab functions. The syntax is help function_name. Another good use of help will come when students begin to create their own Matlab functions. They should not create functions that have the same name as built in Matlab functions. If they do, then the functionality of the built in function will be lost until Matlab is restarted. They can perform a >> help function_name and if Matlab returns help info, they will know that the function already exists as a built in. The lookfor and what commands are useful for Matlab specific files. what searches for Matlab files on a given drive or in a given path. lookfor searches the first comment line of Matlab specific files for the given string and then, if a match is found, displays that first comment line. The clear command removes variables from memory. If clear is supplied with variable names, then only those variables will be removed. It’s a good idea to tell students to type carefully when using clear with arguments. They may want to only clear one variable, but if you hit the <ENTER> key before you get a chance to name the variable, all the variables in memory will be cleared and they may have to start a significant amount of work over. The clc command removes all typing and Matlab output from the command window, but does not do anything to the variables currently stored in the Matlab workspace. clc is particularly useful to clear extraneous information out of the command window prior to doing a problem whose results the students would like to print. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

31 Programación Multimedia
Otros comandos útiles 7- Noviembre what List all m-files in current directory dir List all files in current directory ls Same as dir type test Display test.m in command window delete test Delete test.m cd a: Change directory to a: chdir a: Same as cd pwd Show current directory which test Display current directory path to test.m Instructor notes: More useful commands...what without a drive specified, as on the previous slide, lists all of the m-files in the current directory. The topic of m-files came up on the previous slide very briefly, too. Maybe this is a good time to point out that m-files are essentially Matlab programs and that the students will be dealing with them in the near future as they write small programs that are very much like C/C++ programs. dir and ls list the contents of the current directory. Of course, you can specify a path after the dir or ls and the contents of the directory specified in the path will be displayed. type will display the file specified on the command line in the command window. delete will remove the appropriate file. cd and chdir will allow you to change directories to the one specified following the command. In addition, there are icons at the top of the Matlab window that will allow you to do the same thing. One small window should indicate the present working directory, which is also determined by entering the pwd command in the command window. There is a drop down menu available immediately next to the small window displaying the present working directory that, when click on, will display all recently used directories. This allows for quick transfer between directories. Additionally, the ellipsis icon next to the present working directory window allows for more complete navigation to other directories. The which command followed by a filename displays the path to the specified file. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

32 Operadores relacionales
Programación Multimedia Operadores relacionales 7- Noviembre MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= Instructor notes: Matlab has six relational operators that are used in making comparisons just like in C/C++. It is probably a good thing to emphasize to the students that the relational operators in Matlab are the same as they are in C/C++ EXCEPT for “not equal to” which uses the ~ instead of the ! as part of the operator. Students should be reminded to pay close attention to which language they’re writing in on exams so that they do not mix the two. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

33 Programación Multimedia
Operadores lógicos 7- Noviembre MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or | % equal precedence with and Instructor notes: In addition to the relational operators, Matlab has three logical operators, not, and, and or. A couple differences from C/C++ that are important. First, rather than using the ! for not as in C/C++, the ~ is used. Given the information on the previous slide, this is no surprise. The second difference is that in C/C++ when using logical operators && is a logical and operator and & is a bitwise operator, likewise || is a logical or operator and | is a bitwise operator. However, in Matlab, & and | are logical operators. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

34 Programación Multimedia
Funciones lógicas 7- Noviembre MATLAB also supports some logical functions. xor (exclusive or) Ex: xor (a, b) Where a and b are logical expressions. The xor operator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0. any(x) returns 1 if any element of x is nonzero all(x) returns 1 if all elements of x are nonzero isnan(x) returns 1 at each NaN in x isinf(x) returns 1 at each infinity in x finite(x) returns 1 at each finite value in x Instructor notes: This slide describes some logical functions that Matlab has available. The xor function performs an exclusive or operation on the two logical expressions that it takes as arguments. Thus, xor returns true if and only if one of the expressions is true and the other expression is false. As the slide indicates, true is a 1 and false is a 0. Other logical functions include any, all, isnan, isinf, and finite. any returns true if any element in the item being evaluated is nonzero and all returns true if all of the elements in the item being evaluated are nonzero. isnan, isinf, and finite each return a true at each element in the item being evaluated that is not a number (NaN), infinite, or finite, respectively. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

35 Formatos para mostrar números
Programación Multimedia Formatos para mostrar números 7- Noviembre MATLAB supports 8 formats for outputting numerical results. format long 16 digits format short e 5 digits plus exponent format long e 16 digits plus exponent format hex hexadecimal format bank two decimal digits format + positive, negative or zero format rat rational number (215/6) format short default display Instructor notes: This list describes the display formats that exist in Matlab. The important thing to note here is that the format command only affects the display, it does not affect how values are actually stored. So, there is no benefit in memory to using format short over format long, for example. This list leaves out format compact and format loose which remove and put back in extra line feeds, respectively. The default is format loose. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

36 Estructuras de Selección
Programación Multimedia Estructuras de Selección 7- Noviembre An if - elseif - else structure in MATLAB. Note that elseif is one word. if expression1 %(es verdadera) % execute these commands elseif expression2 %(es verdadera) else %(por defecto) end Instructor notes: Like C/C++ Matlab has an if-elseif-else structure for decision making or branching. There are a few differences between Matlab and C/C++. In Matlab, elseif is one word, rather than two, as it is in C/C++. Curly brackets are not used in Matlab at all, and the end of the if-elseif-else block is denoted with end. Just like in C/C++ expressions are evaluated to be true or false and when an expression evaluates to true, then the statements that correspond to that section of the block are executed. Parentheses are not required around the expression being evaluated. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

37 Estructuras de Repetición
Programación Multimedia Estructuras de Repetición 7- Noviembre A for loop in MATLAB for x = array for x = 1: 0.5 : 10 % execute these commands end A while loop in MATLAB while expression while x <= 10 % execute these commands Instructor notes: Again, as in C/C++ Matlab has looping structures. Matlab has a for loop that is very much like C/C++’s, but with some slight differences. Curly brackets are not needed in Matlab’s for loop. The counter variable is initialized at the beginning of the loop in an assignment statement. Colons are used to separate the initial value from the increment and end point, respectively. If no increment is specified, then it is assumed to be 1. The end statement marks the end of the while loop. The while loop in Matlab is also much like in C/C++, but with some differences. No curly brackets are needed in Matlab and the end of the loop is denoted with the end statement. Matlab does not have a do-while loop like C/C++. It might be a good idea to point out that often in Matlab loops that access arrays begin with 1 rather than 0 as they normally do in C/C++. This is because the first index in a Matlab array is 1 while the first index in a C/C++ array is 0. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

38 Programación Multimedia
Suma Escalar - Matriz 7- Noviembre >> a=3; >> b=[1, 2, 3;4, 5, 6] b = >> c = b+a % Suma a a cada elemento de b c = Instructor notes: The next four slides deal with scalar-matrix math, addition, subtraction, multiplication, and division. In scalar-matrix math the scalar and each individual element of the matrix interact based on the operation being performed. So, if a scalar is being added to a matrix, that scalar will be added to each element in the matrix resulting in a matrix of the same dimensions with each element being modified by the sum of the element and the scalar. Remember, addition and multiplication are commutative, so the order of the operation does not matter. Subtraction and division are not commutative. Also, Matlab will not allow you to divide the scalar by the matrix. It will return an error message indicating that the matrix dimensions do not match. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

39 Programación Multimedia
Resta Escalar - Matriz 7- Noviembre >> a=3; >> b=[1, 2, 3;4, 5, 6] b = >> c = b – a % Resta a de cada elemento de b c = Instructor notes: © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

40 Multiplicación Escalar - Matriz
Programación Multimedia Multiplicación Escalar - Matriz 7- Noviembre >> a=3; >> b=[1, 2, 3; 4, 5, 6] b = >> c = a * b % Multiply each element of b by a c = Instructor notes: c = b * a will produce the same results. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.

41 División Escalar - Matriz
Programación Multimedia División Escalar - Matriz 7- Noviembre >> a=3; >> b=[1, 2, 3; 4, 5, 6] b = >> c = b % Divide each element of b by a c = Instructor notes: c = a/b will produce an error message. © Carlos A. Lázaro Carrascosa. Laboratorio de Comunicación Oral R.W.N. ©Carlos A. Lázaro Carrascosa.


Descargar ppt "Programación Multimedia INTRODUCCIÓN A LA PROGRAMACIÓN EN MATLAB"

Presentaciones similares


Anuncios Google