A Punt Es Intro Ducci On Mat Lab
A Punt Es Intro Ducci On Mat Lab
1.0
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
TABLA DE CONTENIDO
1 Manipulación básica de matrices en MATLAB ............................................................................................................................... 1.1
1.1 Definición de variables.................................................................................................................................................................. 1.1
1.2 Definición de matrices................................................................................................................................................................... 1.2
1.2.1 Operador dos puntos (:) ........................................................................................................................................................ 1.2
1.3 Operaciones con matrices............................................................................................................................................................ 1.3
1.3.1 Operaciones matriciales básicas ......................................................................................................................................... 1.3
1.3.2 Operaciones mixtas ................................................................................................................................................................... 1.4
1.3.3 Operaciones escalares con matrices .................................................................................................................................. 1.4
1.3.4 División inversa .......................................................................................................................................................................... 1.5
1.3.5 Operadores relacionales y lógicos ...................................................................................................................................... 1.6
1.4 Direccionamiento de matrices ................................................................................................................................................... 1.8
1.4.2 Resumen del direccionamiento de matrices ............................................................................................................... 1.10
1.4.3 Matrices vacías ......................................................................................................................................................................... 1.10
1.4.4 Concatenación de matrices por cajas ............................................................................................................................. 1.10
1.4.5 Matrices multidimensionales ............................................................................................................................................ 1.11
1.5 Algunas funciones básicas ........................................................................................................................................................ 1.11
1.5.1 Creación de matrices ............................................................................................................................................................. 1.11
1.5.2 Tamaño ........................................................................................................................................................................................ 1.12
1.5.3 Búsqueda .................................................................................................................................................................................... 1.13
1.5.4 Manejo de matrices ................................................................................................................................................................ 1.14
1.6 Ayuda de MATLAB ....................................................................................................................................................................... 1.14
1.6.1 Operadores y caracteres especiales ................................................................................................................................ 1.14
1.6.2 Funciones matemáticas básicas........................................................................................................................................ 1.15
1.6.3 Operadores aritméticos ........................................................................................................................................................ 1.17
1.6.4 Operadores relacionales y lógicos ................................................................................................................................... 1.18
1.6.5 Creación y manipulación de matrices ............................................................................................................................ 1.19
i
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
1.1
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
inicio marca el primer valor del vector, incremento indica el salto entre elementos, y fin determina cual será
el límite hasta el que incrementaremos el elemento inicial:
>> 1:2:7
ans =
1 3 5 7
En caso de no especificar el incremento se toma 1 como incremento por defecto:
>> 1:4
ans =
1 2 3 4
Tanto el incremento como los valores de inicio y fin pueden ser números reales:
>> 1:0.2:1.8
ans =
1.0000 1.2000 1.4000 1.6000 1.8000
E incluso un número negativo:
>> 5:-1:2
ans =
5 4 3 2
Si al aplicar el incremento se sobrepasa el valor final, el nuevo número calculado no se añade al vector:
>> 1:2:6
ans =
1 3 5
Podemos aplicarlo por filas para definir una matriz:
>> A = [1:5; 6:10]
A =
1 2 3 4 5
6 7 8 9 10
Si fin ya es superior a inicio, el vector que se crea está vacío:
1.2
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
>> v = [5:1:1]
v =
Empty matrix: 1-by-0
>> v = [1:-1:4]
v =
Empty matrix: 1-by-0
9 3 9
7 10 13
11 17 11
Para realizar multiplicaciones será necesario que las columnas del primer operando sean iguales a las filas del
segundo:
>> A * B
ans =
26 38 26
71 83 71
116 128 116
Estas dimensiones deben coincidir incluso en el caso de vectores. No es lo mismo un vector fila que uno columna.
>> x = [1 2 3]
x =
1 2 3
>> y = [2;3;4]
y =
2
3
1.3
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
4
>> x+y
??? Error using ==> plus
Matrix dimensions must agree.
>> x+y'
ans =
3 5 7
La traspuesta no tiene restricciones dimensionales, mientras que la potencia necesita que la matriz sea cuadrada.
La operación división de matrices lo que hace es multiplicar por la inversa de la matriz por la que estamos
dividiendo, de modo que A/B es equivalente a A*inv(B)1, donde inv es una función que calcula la inversa de la
matriz:
>> A = magic(3);
>> B = [1 2 3; 3 1 2; 2 4 3];
>> A/B
ans =
1.0000 3.0000 -1.0000
2.0000 0.2000 0.2000
-3.0000 -0.2000 3.8000
>> A*inv(B)
ans =
1.0000 3.0000 -1.0000
2.0000 0.2000 0.2000
-3.0000 -0.2000 3.8000
La división inversa se detalla más adelante.
1Esta división se puede utilizar aunque la matriz derecha no sea cuadrada. En ese caso se calcula la pseudoinversa de la matriz
por la que se está dividiendo, se multiplica por ella, y después se deshace la pseudoinversa:
>> A = magic(3);
>> B = [1 2 3; 3 1 2];
B =
1 2 3
3 1 2
>> A/B
ans =
-0.2000 2.8000
2.2400 0.2400
1.5600 0.5600
1.4
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
Sin embargo, nosotros no queremos hacer una multiplicación matricial, sino multiplicar cada uno de los elementos
por separado. Para ello tenemos que anteponer un ‘.’ a la operación que queremos realizar:
>> y = sqrt(1-x.*x)
y =
Columns 1 through 8
0 0.4359 0.6000 0.7141 0.8000 0.8660 0.9165 0.9539
Columns 9 through 16
0.9798 0.9950 1.0000 0.9950 0.9798 0.9539 0.9165 0.8660
Columns 17 through 21
0.8000 0.7141 0.6000 0.4359 0
Así ya podríamos dibujar el círculo y ajustar los ejes para que se vea con relación de aspecto 1:1:
>> plot(x,y)
>> axis equal
1.2
0.8
0.6
0.4
0.2
-0.2
El operador de multiplicación escalar de matrices (punto ‘.’) se puede anteponer a las operaciones de multiplicación
(‘.*’), división (‘./’), división inversa (‘.\’) y potencia (‘.^’).
Para consultar la ayuda acerca de estos operadores, podéis escribir
>> help arith
1.5
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
• Sistema indeterminado (más incógnitas que ecuaciones): Da una de las infinitas soluciones válidas (hace cero
una de las incógnitas y calcula las otras dos)
>> A =[1 1 3; 1 2 4], b = [0;1]
A =
1 1 3
1 2 4
b =
0
1
>> A\b
ans =
0
1.5000
-0.5000
• Sistema sobredeterminado (más ecuaciones que incógnitas): obtiene una solución del sistema en el sentido
de minimizar el error cuadrático medio, ya que no es un sistema que tenga solución.
>> A =[1 1; 1 2; 3 4], b = [0;1;2]
A =
1 1
1 2
3 4
b =
0
1
2
>> x = A\b
x =
-0.5000
0.8333
• Incompatible: no existe solución al sistema.
>> A =[1 1; 2 2], b = [0;1]
A =
1 1
2 2
b =
0
1
>> x = A\b
Warning: Matrix is singular to working precision.
x =
-Inf
Inf
1.6
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
B =
1 0 1
0 1 1
0 1 0
>> whos A ans
Name Size Bytes Class Attributes
A 3x3 72 double
B 3x3 9 logical
Esos elementos de tipo lógico se pueden utilizar como variables booleanas en expresiones relacionadas por
operadores lógicos. Por ejemplo, si calculamos en otra matriz qué elementos son menores que 6
>> C = A < 6
C =
0 1 0
1 1 0
1 0 1
Y luego hacemos la intersección de ambos con un AND
>> B & C
ans =
0 0 0
0 1 0
0 0 0
Tenemos que el único elemento que es mayor que 4 y menor que 6 es el 5. También lo podríamos haber calculado
como
>> (A > 4) & (A < 6)
ans =
0 0 0
0 1 0
0 0 0
Es importante tener en cuenta que el lenguaje matemático no siempre se puede escribir directamente como
comandos de MATLAB. Por ejemplo, para decir que un número está entre 4 y 6, matemáticamente podemos
expresarlo como 4<A<6. Sin embargo, al escribir esto en línea de comandos tenemos:
>> 4<A<6
ans =
1 1 1
1 1 1
1 1 1
¿Qué ha ocurrido? La línea 4<A<6 contiene dos operaciones distintas de MATLAB, puesto que tiene dos operadores
relacionales. MATLAB realiza primero la comparación 4<A, y después compara el resultado con 6. Si dividimos el
proceso en dos pasos, vemos que MATLAB primero compara los contenidos de A con el número 4:
>> 4<A
ans =
1 0 1
0 1 1
0 1 0
El segundo paso consiste en comparar los resultados de la operación anterior (ans) con el número 6. Como ans, al
contener el resultado de una comparación, sólo tiene unos y ceros, todos los elementos de ans son menores que 6:
>> ans<6
ans =
1 1 1
1 1 1
1 1 1
Para ver la ayuda referente a estos operadores debéis teclear
>> help relop
1.7
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
2 En el caso de que estemos trabajando con vectores, utilizamos un único índice para acceder a sus elementos, ya que son
estructuras de datos que tienen una sola dimensión: v(2) sería el segundo elemento del vector v.
3 Es decir, que MATLAB no puede leer valores fuera del tamaño actual de la matriz (¿Cuánto valdrían?), pero sí que puede asignar
1.8
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
1.9
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
= −− ,
Para poder combinar esas tres matrices (D, B y la matriz de ceros, Z) necesitamos crear una matriz con B y Z, para
que unamos dos matrices con 6 filas cada una (coherencia dimensional). Para ello definimos una matriz DENTRO
de otra como sigue
>> E = [D, [B; zeros(3)]]
E =
1 2 3 8 1 6
1.10
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
4 5 6 3 5 7
7 8 9 4 9 2
8 1 6 0 0 0
3 5 7 0 0 0
4 9 2 0 0 0
1.11
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
1.5.1.1 EJERCICIOS
Crear en MATLAB las siguientes matrices en una única línea de comandos sin escribirlas directamente.
A = G =
0 0 0 0 0 0 0 6 0
0 0 0 0 0 0 0 0 5
0 0 0 0 0 0 0 0 0
B = I =
1 0 0 0 3 3 3 3
0 1 0 0 3 3 3 3
0 0 1 0
0 0 0 1
C = J =
1 1 1 1 2 3
1 1 1 1 2 3
1 1 1 1 2 3
1 1 1
D = K =
1 0 0 0 0 3 4 5 6 7
0 1 0 0 0 6 8 10 12 14
0 0 1 0 0 9 12 15 18 21
E = L =
0 1 1 1 1 1 1/2 1/3
1 0 1 0 1 1/2 1/4 1/6
1 1 0 1 0 1/3 1/6 1/9
F = M =
0 0 0 0 0 1 1 1 1
1 0 0 0 0 1 2 3 4
0 2 0 0 0 1 4 9 16
0 0 3 0 0 1 8 27 64
1.5.2 TAMAÑO
Es muy útil, y en gran número de cálculos necesario, saber el tamaño de los vectores y/o matrices con los que
estamos trabajando. MATLAB nos proporciona varios modos para conocer este(os) valor(es).
El primero es el comando whos:
>> whos
Name Size Bytes Class Attributes
A 3x4 96 double
B 3x2 48 double
C 2x3 48 double
D 0x0 0 double
a 1x1 8 double
ans 2x2 32 double
b 2x1 16 double
k 1x4 32 double
x 1x7 56 double
y 1x4 32 double
Otro método consiste simplemente en añadir la columna ‘Size’ en la ventana ‘Workspace’ del entorno gráfico de
MATLAB, de manera que nos aparecerá automáticamente el tamaño de cada variable en dicha ventana.
Sin embargo, a la hora de programar utilizando el lenguaje M de MATLAB, el más habitual, y el único que es
realmente útil, es la función size que devuelve un vector con el tamaño en filas y columnas de una matriz.
>> size(A)
ans =
3 4
Podemos pedir sólo las filas.
>> size(A,1)
ans =
3
1.12
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
1.5.3 BÚSQUEDA
La función find busca elementos de una matriz que cumplan una determinada condición y devuelve sus índices:
>> x = -3:3
x =
-3 -2 -1 0 1 2 3
>> k = find(abs(x)>1)
k =
1 2 6 7
Estos índices se pueden utilizar para ver cuánto valían esos elementos.
>> y = x(k)
y =
-3 -2 2 3
Si trabajamos con matrices nos devuelve los índices desarrollando la matriz como un vector (por columnas)
>> A = magic(3)
A =
8 1 6
3 5 7
4 9 2
>> find(A<4)
ans =
2
4
9
>> A(ans)
ans =
3
1
2
A menos que le pidamos expresamente que nos dé los índices en forma de filas y columnas.
>> [f,c] = find(A<4)
f =
2
1
3
c =
1
2
3
1.13
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
Arithmetic operators.
plus - Plus +
uplus - Unary plus +
minus - Minus -
uminus - Unary minus -
mtimes - Matrix multiply *
times - Array multiply .*
mpower - Matrix power ^
power - Array power .^
mldivide - Backslash or left matrix divide \
mrdivide - Slash or right matrix divide /
ldivide - Left array divide .\
rdivide - Right array divide ./
kron - Kronecker tensor product kron
Relational operators.
eq - Equal ==
ne - Not equal ~=
lt - Less than <
gt - Greater than >
le - Less than or equal <=
ge - Greater than or equal >=
Logical operators.
relop - Short-circuit logical AND &&
relop - Short-circuit logical OR ||
and - Element-wise logical AND &
or - Element-wise logical OR |
not - Logical NOT ~
xor - Logical EXCLUSIVE OR
any - True if any element of vector is nonzero
all - True if all elements of vector are nonzero
Special characters.
colon - Colon :
paren - Parentheses and subscripting ( )
1.14
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
paren - Brackets [ ]
paren - Braces and subscripting { }
punct - Function handle creation @
punct - Decimal point .
punct - Structure field access .
punct - Parent directory ..
punct - Continuation ...
punct - Separator ,
punct - Semicolon ;
punct - Comment %
punct - Invoke operating system command !
punct - Assignment =
punct - Quote '
transpose - Transpose .'
ctranspose - Complex conjugate transpose '
horzcat - Horizontal concatenation [,]
vertcat - Vertical concatenation [;]
subsasgn - Subscripted assignment ( ),{ },.
subsref - Subscripted reference ( ),{ },.
subsindex - Subscript index
metaclass - Metaclass for MATLAB class ?
Bitwise operators.
bitand - Bit-wise AND.
bitcmp - Complement bits.
bitor - Bit-wise OR.
bitmax - Maximum floating point integer.
bitxor - Bit-wise XOR.
bitset - Set bit.
bitget - Get bit.
bitshift - Bit-wise shift.
Set operators.
union - Set union.
unique - Set unique.
intersect - Set intersection.
setdiff - Set difference.
setxor - Set exclusive-or.
ismember - True for set member.
Trigonometric.
sin - Sine.
sind - Sine of argument in degrees.
sinh - Hyperbolic sine.
asin - Inverse sine.
asind - Inverse sine, result in degrees.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosd - Cosine of argument in degrees.
cosh - Hyperbolic cosine.
acos - Inverse cosine.
acosd - Inverse cosine, result in degrees.
1.15
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
Exponential.
exp - Exponential.
expm1 - Compute exp(x)-1 accurately.
log - Natural logarithm.
log1p - Compute log(1+x) accurately.
log10 - Common (base 10) logarithm.
log2 - Base 2 logarithm and dissect floating point number.
pow2 - Base 2 power and scale floating point number.
realpow - Power that will error out on complex result.
reallog - Natural logarithm of real number.
realsqrt - Square root of number greater than or equal to zero.
sqrt - Square root.
nthroot - Real n-th root of real numbers.
nextpow2 - Next higher power of 2.
Complex.
abs - Absolute value.
angle - Phase angle.
complex - Construct complex data from real and imaginary parts.
conj - Complex conjugate.
imag - Complex imaginary part.
real - Complex real part.
unwrap - Unwrap phase angle.
isreal - True for real array.
cplxpair - Sort numbers into complex conjugate pairs.
1.16
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
- Minus.
X - Y subtracts matrix X from Y. X and Y must have the same
dimensions unless one is a scalar. A scalar can be subtracted
from anything.
* Matrix multiplication.
X*Y is the matrix product of X and Y. Any scalar (a 1-by-1 matrix)
may multiply anything. Otherwise, the number of columns of X must
equal the number of rows of Y.
.* Array multiplication
X.*Y denotes element-by-element multiplication. X and Y
must have the same dimensions unless one is a scalar.
A scalar can be multiplied into anything.
^ Matrix power.
Z = X^y is X to the y power if y is a scalar and X is square. If y is an
integer greater than one, the power is computed by repeated
multiplication. For other values of y the calculation
involves eigenvalues and eigenvectors.
Z = x^Y is x to the Y power, if Y is a square matrix and x is a scalar,
computed using eigenvalues and eigenvectors.
Z = X^Y, where both X and Y are matrices, is an error.
.^ Array power.
Z = X.^Y denotes element-by-element powers. X and Y
must have the same dimensions unless one is a scalar.
A scalar can operate into anything.
1.6.3.1 AYUDA DE LA DIVISIÓN NORMAL E INVERTIDA
>> help slash
Matrix division.
\ Backslash or left division.
A\B is the matrix division of A into B, which is roughly the
same as INV(A)*B , except it is computed in a different way.
If A is an N-by-N matrix and B is a column vector with N
components, or a matrix with several such columns, then
X = A\B is the solution to the equation A*X = B computed by
Gaussian elimination. A warning message is printed if A is
badly scaled or nearly singular. A\EYE(SIZE(A)) produces the
inverse of A.
If A is an M-by-N matrix with M < or > N and B is a column
vector with M components, or a matrix with several such columns,
then X = A\B is the solution in the least squares sense to the
under- or overdetermined system of equations A*X = B. The
1.17
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
1.18
INFORMÁTICA: NOTAS DE CLASE
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB
Elementary matrices.
zeros - Zeros array.
ones - Ones array.
eye - Identity matrix.
repmat - Replicate and tile array.
rand - Uniformly distributed random numbers.
randn - Normally distributed random numbers.
linspace - Linearly spaced vector.
logspace - Logarithmically spaced vector.
freqspace - Frequency spacing for frequency response.
meshgrid - X and Y arrays for 3-D plots.
accumarray - Construct an array with accumulation.
: - Regularly spaced vector and index into matrix.
Matrix manipulation.
cat - Concatenate arrays.
reshape - Change size.
diag - Diagonal matrices and diagonals of matrix.
blkdiag - Block diagonal concatenation.
tril - Extract lower triangular part.
triu - Extract upper triangular part.
fliplr - Flip matrix in left/right direction.
flipud - Flip matrix in up/down direction.
flipdim - Flip matrix along specified dimension.
rot90 - Rotate matrix 90 degrees.
: - Regularly spaced vector and index into matrix.
find - Find indices of nonzero elements.
end - Last index.
sub2ind - Linear index from multiple subscripts.
ind2sub - Multiple subscripts from linear index.
bsxfun - Binary singleton expansion function.
1.19
MANIPULACIÓN BÁSICA DE MATRICES EN MATLAB INFORMÁTICA: NOTAS DE CLASE
Specialized matrices.
compan - Companion matrix.
gallery - Higham test matrices.
hadamard - Hadamard matrix.
hankel - Hankel matrix.
hilb - Hilbert matrix.
invhilb - Inverse Hilbert matrix.
magic - Magic square.
pascal - Pascal matrix.
rosser - Classic symmetric eigenvalue test problem.
toeplitz - Toeplitz matrix.
vander - Vandermonde matrix.
wilkinson - Wilkinson's eigenvalue test matrix.
1.20