Matrices Contextualizado
Matrices Contextualizado
net/publication/267789660
Notas de MatLab @
Article
CITATION
S READS
0 304
All content following this page was uploaded by Mario Medina-Valdez on 25 March 2015.
Departamento de
Matemáticas Universidad
Autónoma Metropolitana-
Iztapalapa
Av San Rafael Atlixco 186
Col. Vicentina
México DF CP 09340
MEXICO
>> quit
>> exit
Caracteres especiales
>> B=[2,4,1;-5,3,-1]
B=
2 4 1
-5 3 -1
Las tres primeras entradas están separadas por comas (,), al igual que
las últimas tres, pero las tres primeras están separadas de las tres
últimas por un punto y coma (;), éste último signo nos separa los
renglones de la matriz. Otra forma de obtener la misma matriz es dejar
espacios en blanco entre las tres primeras entradas en lugar de poner
una coma. Lo que no debemos olvidar es el punto y coma que divida los
renglones.
B=
2 4 1
-5 3 -1
IMPORTANTE: Si deseamos que no se imprima la respuesta o salida
debemos usar un punto y coma después del comando
>> B=[2,4,1;-5,3,-1];
>> C=[1,2;4,3]
C=
1 2
4 3
>> d=det(C)
d=
-5
>> D=inv(C)
D=
-0.6000 0.4000
0.8000 -0.2000
>> I=C*D
I=
1 0
0 1
Si una matriz C es invertible, el cual es el caso de la matriz entonces
podemos resolver el sistema lineal de ecuaciones Cx=B y en tal caso, X
= (1/C)B, o, usando la notación de Matlab tenemos que, X = C\B.
Intentemos resolver el sistema Cx = B, con la matriz C dada
anteriormente y B= [ 1; 1 ]. Observemos que el vector B es un vector
columna.
>> B=[1;1]
B=
1
1
>> x=C\B
x=
-0.2000
0.6000
>> C*x
Obtenemos la matriz
ans =
1
1
>> A=[1,2;4,3]
A=
1 2
4 3
>> A'
ans =
1 4
2 3
>> rank(A)
ans =
>> rref(A)
ans =
1 0
0 1
>> [w,lambda]=eig(A)
w=
-0.7071 -0.4472
0.7071 -0.8944
lambda =
-1 0
0 5
También podemos referirnos a una entrada en particular de la matriz A
usando el comando A(m,n), el cual nos regresa el número que se
encuentra en la entrada correspondiente al renglón m y la columna n.
>> A(1,2)
ans =
Consideremos la matriz
>> M=[1,2,3;4,5,6;7,8,0]
M=
1 2 3
4 5 6
7 8 0
ans =
2
5
8
>> M(3,:)
ans =
7 8 0
ans =
2 3
5 6
>> v=[-1,pi,-2]'
v=
-1.0000
3.1416
-2.0000
>> [M,v]
ans =
>> [M;v']
ans =
M=
1 2 3
7 8 0
Indexación lógica:
>> N=magic(3)
N=
8 1 6
3 5 7
4 9 2
>> N>3
ans =
1 0 1
0 1 1
1 1 0
ans =
8 6 1
3 7 5
4 2 9
B ans =
8 1
3 5
4 9
>> A = magic(4)
A=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> L = zeros(4,4)
L=
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
>> L(A>8) = 1
L=
1 0 0 1
0 1 1 0
1 0 0 1
0 1 1 0
La matriz L de tamaño 4x4 que está arriba indica cuales son las
entradas de A que son mayores que 8 a través de la expresión ( L(i,j) =
1 ). Podemos obtener la misma matriz de otra forma,
>> K = A>8
K=
1 0 0 1
0 1 1 0
1 0 0 1
0 1 1 0
Al considerar la matriz
>> A=[1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16]
A=
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
>> sum(A,1)
ans =
28 32 36 40
ans =
10
26
42
58
Herramientas útiles:
El comando who nos dirá cuales han sido todas las variables que han
sido definidas en la sesión en que se trabaja.
>> who
M ans b v
>> whos
Name Size Bytes Class
>> pi
ans =
3.1416
El comando eps es una función que nos regresa el número más pequeño
de punto flotante de MatLab. Esto es útil si se tiene un vector que
pudiese contener ceros y se usará para como denominador de algo. Si
se le añade eps al vector no se le
añade nada significativo al vector, pero no tendremos problemas al
dividir por cero.
A=
1 0
0 2
Y a continuación el comando
>> n=[1;1]
n=
1
1
n=
1
2
n=
1
4
n=
1
8
n=
1
16
n=
1
32
de x, Damos el valor de x
>> x=3
x=
x=
13
x=
63
x=
313
x=
1563
x=
7813
ARREGLOS
Las matrices que hemos visto anteriormente son ejemplos de los que se
llaman arreglos (arrays en inglés)
>> x=[0,0.1*pi,0.2*pi,0.3*pi,0.4*pi]
x=
Podemos calcular sin(x) para cada uno de los valores del arreglo y
obtener un nuevo arreglo y:
>> y=sin(x)
y=
>> z=x+y
z=
>> w=1.5*x+2
w=
>> v=x.^2
v=
>> b=x.*v
b=
>> m=2.^[2,3,4]
m=
4 8 16
>> 2^[2,3,4]
??? Error using ==> ^
Matrix must be square.
Longitud de un arreglo
>> length(m)
ans =
>> v.^b
ans =
>> x=linspace(0,pi,7)
x=
>> x=linspace(0,pi,13)
x=
Columns 1 through 7
Columns 8 through 13
>> x=0:0.2:pi
Columns 1 through 7
Columns 8 through 14
Columns 15 through 16
2.8000 3.0000
>> a=1:10
a=
1 2 3 4 5 6 7 8 9 10
>> b=0:2:20
b=
0 2 4 6 8 10 12 14 16 18 20
>> v(1)
ans =
0
>> v(3)
ans =
0.3948
>> v(2:5)
ans =
>> v(3:end)
ans =
>> cat(3,M,M)
ans(:,:,1) =
1 2 3
7 8 0
ans(:,:,2) =
1 2 3
7 8 0
M=
1 2 3
4 5 6
7 8 0
>> cat(3,M,M)
ans(:,:,1) =
1 2 3
4 5 6
7 8 0
ans(:,:,2) =
1 2 3
4 5 6
7 8 0
Si queremos construir una gráfica que una los puntos del plano dados
por (0,-1), (1,4), (2,.3) y (3,6), los cuales están conectados por
segmentos de recta es necesario dar los arreglos de las primeras y
segundas coordenadas de los puntos y usar el comando plot:
>> x=[0,1,2,3];y=[-1,4,-3,6];plot(x,y)
>> x=linspace(0,2*pi,100);
Posteriormente hay que generar otro arreglo, pero este consta del
arreglo que se obtiene de evaluar sin(x) para cada uno de los elementos
del arrglo x
>> y=sin(x);
>>plot(x,y)
Obteniendo la gráfica
Dos bosquejos de funciones de variable real en un mismo gráfico
>> x=linspace(-pi,pi,100);
>> y=sin(x);
>> z=cos(x);
>> plot(x,y,x,z)
La sucesión de comandos
>> x=linspace(-pi,pi,100);
>> y=sin(x);
>> z=cos(x);
>> plot(x,y,x,z);grid
El primer comando nos permite crear una matriz cuyas entradas son los
puntos una celosía o rejilla del cuadrado -2 <= x <= 2, -2 <= y <= 2.
Los cuadrados pequeños miden 0.2 unidades de ancho y 0.2 unidades
de altura; el segundo comando crea una matriz cuyas entradas son los
valores de la función z(x,y) en los puntos de la celosía. Finalmente el
tercer comando construye la gráfica usando los dos arreglos obtenidos
previamente.
Otro uso de meshgrid (Campo de direcciones de un campo vectorial):
La sucesión de comandos
>> [x,y]=meshgrid(-2:0.1:2);
>> u=-y;v=x;
>> quiver(x,y,u,v)
Quiver plot dibuja los vectores velocidad como flechas con componentes
(u,v) en los puntos (x,y). Las matrices X,Y,U,V deben tener el mismo
tamaño y contener los correspondientes componentes de posición y de
velocidad (X y Y pueden ser también vectores que especifiquen una
rejilla uniforme). Quiver muestra las flechas a escala para que quepan
en la rejilla.
Usamos
>> [x,y]=meshgrid(-
2:0.5:2); u=-y;v=x;
quiver(x,y,u,v,0)
>> [x,y]=meshgrid(-2:0.5:2);
u=-y;v=x;
quiver(x,y,u,v)
[x,y] = meshgrid(-2:.2:2,-1:.15:1);
z = x .* exp(-x.^2 - y.^2); [px,py] = gradient(z,.2,.15);
contour(x,y,z), hold on
quiver(x,y,px,py), hold off, axis image
Funciones (functions) y escritos (scripts)
>> cd c:\dir1\dir2\dir3
>>
>> gauss.m
Para escribir este tipo de archivos podemos usar el editor de textos que
acompaña a MatLab.
Archivos scritp
En el caso del primer tipo de m-archivos, los archivos script, éstos se
usan si necesitamos efectuar una tarea que consista de distintos pasos.
Cuando se lee un archivo tipo script los comandos escritos en este se
interpretan de manera literal como si estuvieran escritos en la ventana
de comandos. Los archivos script permiten dar una lista larga de
comandos que puede ser revisada en cualquier momento directamente
en el archivo script, además podemos realizar la misma tarea
posteriormente sin tener que escribir renglón por renglón la sucesión de
comandos en la ventana de comandos, entre otros aspectos
convenientes.
X=linspace(-pi,pi,200);
Y=sin(X);
plot(X,y);
title(‘gráfica de la funcion seno’);
axis([-pi pi –1.5 1.5]);
Como se comentó anteriormente, debemos tener cuidado con la
trayectoria del archivo y donde lo guardamos. Finalmente en la ventana
de comandos llamamos el archivo
>> seno
Archivos función
Los archivos función permiten usar MatLab a una mayor capacidad que
utilizando solamente la ventana de comandos.
Todo archivo-función debe comenzar con una primera línea del tipo siguiente
Las variables ent1, 1nt2 y ent3 son argumentos de entrada, mientras que
salida1, salida2 son argumentos de salida. Una función puede tener tantos
argumentos de entrada y de salida como se desee y llamarlos cuando
éstos se necesiten. Es muy importante observar que el nombre mifunción
de la función debe ser exactamente igual al nombre del archivo.
Por ejemplo podemos crear en el editor un archivo llamado cubica.m donde definiremos
una función con el mismo nombre cubica tecleando en el editor la siguiente lista de
comandos y procedemos posteriormente a guardar el archivo con el nombre mencionado
function cubica=f(x)
cubica=x.^3;
>> cubica(1.1)
ans =
1.3310
ans =
>>x=[1:0.1:5];
>>y=cubica(x);
>>plot(x,y)
function [A]=area(a,b,c)
donde A representa un único dato de salida y a,b y c son los tres datos de
entrada. Podemos usar el símbolo de porcentaje % para escribir
comentarios, por ejemplo, sobre las características de la función que
estamos definiendo lo que le permita a cualquier usuario entender todo
el proceso que estemos siguiendo
function [A]=area(a,b,c)
%Calculamos al area de un triangulo cuyos lados son a,b y c
% entradas son las longitudes de los lados : a,b,c
% salida es el area A calculada para el triangulo
s=(a+b+c)/2; % s=promedio de las longitudes de los lados
del triangulo A=sqrt(s*(s-a)*(s-b)*(s-c));
>> area(3,4,5)
ans =
>> a=0,b=2*pi,N=100,w=3
a=
b=
6.2832
N=
100
w=
>> senito
y la gráfica que obtenemos es la siguiente
Otro ejemplo:
x=0:2*pi/N:2*pi;
y=cos(x);
z=funcion(x);
plot(x,y,x,z)
>> otrafuncion
y yellow . punto
m magenta o círculo
c cyan x cruces
r rojo + signos de suma
g verde - línea sólida
b azul * estrellas
k negro : línea punteada
w blanco _. punto y línea
-- línea
discontinua
Por ejemplo,
>> plot(x,y,’r’)
>> plot(x,y,’b:’)
x=-pi:2*pi/100:2*pi;
y=cos(x);
plot(x,y,'g.-',x, sin(x),'b--');
xlabel('eje x');
ylabel('eje y');
title('Las graficas de coseno y seno');
axis([-pi pi -1.5 1.5]);
grid;
legend('grafica coseno','grafica de seno');
function Y=func(X)
% Entrada est´a dada por un arreglo X
% Salida esta dada por un arreglo que resulta
% de aplicar la funcion f(x)=sen(x^2)/(1+2x^2) a todos los elementos de X
Y=sin(X.^2)./(1+2*X.^2);
x=[0:0.1:4*pi];
y=func(x);
plot(x,y,'r')
title('Grafica de la funcion f(x)=sin(x^2)/(1+2x^2)')
axis([0 14 –0.15 0.3])
xlabel(‘eje x’)
ylabel(‘eje y’)
Programación en Matlab
Operadores de relación:
== Igual que
~= No igual que
< Menor que
> Mayor que
>= Mayor o igual que
<= Menor o igual
Sintaxis de for:
Sintaxis de if:
if (premisa)
Instrucciones ejecutables
else
Instrucciones ejecutables
end
Sintaxis de while:
while (premisa)
Instrucciones ejecutables
end
for i=1:6
M(i,1)=3;M(1,i)=3;
%las entradas del primer renglon y la
%primera columna de una matriz 6x6 son 3's
end
for i=2:6
for j=2:6
M(i,j)=M(i,j-1)+M(i-1,j);
end
end
% a partir de las entradas del primer renglon y la primera columna
% completamos la matriz 6x6 de tal forma que la entrada (i,j) se obtiene de sumar
% las entradas (i,j-1) y (i-1,j)
M
% se pide escribir la matriz final M
Ahora en la ventana de comandos tecleemos el nombre del archivo
>>sumas
y obtenemos la matriz M
>> sumas
M=
3 3 3 3 3 3
3 6 9 12 15 18
3 9 18 30 45 63
3 12 30 60 105 168
3 15 45 105 210 378
3 18 63 168 378 756
for i=1:150
x=i^(1/3);
% calcularemos las raices de 1 a 150, pero si en algun momento
% despues de i igual a 10 se tiene tambien que la raiz cubica del numero menos el
%mayor
% entero menor o igual a tal raiz se anula, detenemos los
calculos if((i>10)&(x-floor(x)==0))
break
end
end
i
>> corte
i=
27
N=20;
i=10;
% a partir de 10 hasta veinte de 1 en 1 calculamos sin(3*pi/i) y se muestra este
%numero, su cuadrado y su cubo respectivamente
while i<=N
x=sin(3*pi/i); disp([ 'seno', 'cuadrado', 'cubo']), disp([ x x^2 x^3]), i=i+1;
end
El resultado obtenido es
>> mostrar
senocuadradocubo
0.8090 0.6545 0.5295
senocuadradocubo
0.7557 0.5712 0.4317
senocuadradocubo
0.7071 0.5000 0.3536
senocuadradocubo
0.6631 0.4397 0.2916
senocuadradocubo
0.6235 0.3887 0.2424
senocuadradocubo
0.5878 0.3455 0.2031
senocuadradocubo
0.5556 0.3087 0.1715
senocuadradocubo
0.5264 0.2771 0.1459
senocuadradocubo
0.5000 0.2500 0.1250
senocuadradocubo
0.4759 0.2265 0.1078
senocuadradocubo
0.4540 0.2061 0.0936
Uso de rutinas de Matlab para resolver EDOs
function z=f1(t,y)
z=y^2+2/(2+2*t^3)*cosy;
˙x˙ - (1 - x 2 ) x˙ x 0
Let’s choose y1 = x and y2 =
dx/dt canonical form:
y˙ 1 y 2
y˙ 2 (1 - 1y 2 )2 - y1
y
Save this file with the same name as the name of the function (‘vdpolfun.m’ here).
To solve the ODE, use the following in a new M-file (vdpol.m):
You can also identify the specific solution time points desired by adding them to tspan.
For example:
tspan = linspace(0,20,100);
[t, y] = ode45(‘vdpolfun’, tspan, y0);
For = 10, ode45 works fine. Now, solve the van der Pol equation for mu = 100 and for a
time span from 0 to 3000. What happens? What do you propose to solve this equation?
Exercises
Exercise 1 (Reactions in series):
Using Matlab, find the concentrations of A, B, and C for the following reactions:
A k1 B k2 C
b) Integrate these differential equations for the time between 0 and 5. Plot the results.
Compare with the analytical solution.
c) We decide to add a temperature ramp: T = 298 + 100 * t
Sintaxis
[T,Y] = rutina(odefun,tspan,y0)
[T,Y] = rutina(odefun,tspan,y0,opciones)
[T,Y] = rutina(odefun,tspan,y0,opciones,p1,p2...)
[T,Y,TE,YE,IE] = rutina(odefun,tspan,y0,opciones)
sol = rutina(odefun,[t0 tf],y0...)
donde rutina puede ser: ode45, ode23, ode113, ode15s, ode23s, ode23t, or ode23tb.
Argumentos
Odefun A function that evaluates the right-hand side of the differential equations. All
solvers solve systems of equations in the form or problems that
involve a mass matrix, . The ode23s solver can
solve only equations with constant mass matrices. ode15s and ode23t can
solve problems with a mass matrix that is singular, i.e., differential-
algebraic equations (DAEs).
Tspan A vector specifying the interval of integration, [t0,tf]. To obtain solutions at
specific times (all increasing or all decreasing), use tspan = [t0,t1,...,tf].
y0 A vector of initial conditions.
options Optional integration argument created using the odeset function. See odeset
for details.
p1,p2... Optional parameters that the solver passes to odefun and all the functions
specified in options..
Descripción
Corresponding entries in TE, YE, and IE return, respectively, the time at which an event
occurs, the solution at the time of the event, and the index i of the event function that
vanishes.
sol = solver(odefun,[t0 tf],y0...) returns a structure that you can use with deval
to evaluate the solution at any point on the interval [t0,tf]. You must pass odefun as a
function handle. The structure sol always includes these fields:
sol.x Steps chosen by the solver.
sol.y Each column sol.y(:,i) contains the solution at
sol.x(i). sol.solver Solver name.
If you specify the Events option and events are detected, sol also includes these fields:
sol.xe Points at which events, if any, occurred. sol.xe(end) contains the exact point
of a terminal event, if any.
sol.ye Solutions that correspond to events in sol.xe.
sol.ie Indices into the vector returned by the function specified in the Events option.
The values indicate which event the solver detected.
If you specify an output function as the value of the OutputFcn property, the solver calls it
with the computed solution after each time step. Four output functions are provided:
odeplot, odephas2, odephas3, odeprint. When you call the solver with no output
arguments, it calls the default odeplot to plot the solution as it is computed. odephas2
and odephas3 produce two- and three-dimnesional phase plane plots, respectively.
odeprint displays the solution components on the screen. By default, the ODE solver
passes all components of the solution to the output function. You can pass only specific
components by providing a vector of indices as the value of the OutputSel property. For
example, if you call the solver with no output arguments and set the value of OutputSel to
[1,3], the solver plots solution components 1 and 3 as they are computed.
For the stiff solvers ode15s, ode23s, ode23t, and ode23tb, the Jacobian matrix is
critical to reliability and efficiency. Use odeset to set Jacobian to @FJAC if FJAC(T,Y)
returns the Jacobian or to the matrix if the Jacobian is constant. If the
Jacobian property is not set (the default), is approximated by finite differences. Set
the Vectorized property 'on' if the ODE function is coded so that odefun(T,[Y1,Y2 ...])
returns [odefun(T,Y1),odefun(T,Y2) ...]. If is a sparse matrix, set the JPattern
property to the sparsity pattern of , i.e., a sparse matrix S with S(i,j) = 1 if the
ith component of depends on the jth component of , and 0 otherwise.
The solvers of the ODE suite can solve problems of the form , with
time- and state-dependent mass matrix . (The ode23s solver can solve only
equations with constant mass matrices.) If a problem has a mass matrix, create a
function M = MASS(t,y) that returns the value of the mass matrix, and use odeset to
set the Mass
property to @MASS. If the mass matrix is constant, the matrix should be used as the value of
the Mass property. Problems with state-dependent mass matrices are more difficult:
If the mass matrix does not depend on the state variable and the function MASS
is to be called with one input argument, t, set the MStateDependence property to
'none'.
If the mass matrix depends weakly on , set MStateDependence to 'weak' (the
default) and otherwise, to 'strong'. In either case, the function MASS is called
with the two arguments (t,y).
Return a sparse .
Supply the sparsity pattern of using the JPattern property or a
sparse using the Jacobian property.
For strongly state-dependent , set MvPattern to a sparse matrix S with
S(i,j) = 1 if for any k, the (i,k) component of depends on component j
of , and 0 otherwise.
The algorithms used in the ODE solvers vary according to order of accuracy [6] and the
type of systems (stiff or nonstiff) they are designed to solve. See Algorithms for more
details.
Options
Different solvers accept different parameters in the options list. For more information, see
odeset and Improving ODE Solver Performance in the "Mathematics" section of the
MATLAB documentation.
MaxStep, InitialStep
Jacobian, JPattern, -- -- --
Vectorized
Mass
MStateDependence
MvPattern
--
MassSingular -- -- -- --
-- -- -- -- --
InitialSlope -- -- -- -- --
MaxOrder, BDF -- -- -- -- -- --
Un ejemplo de un sistema no rígido está dado por la descripción de un movimiento rígido
sin fuerzas externas
Para ello creamos un archivo tipo función que defina el sistema de ecuaciones diferenciales
y llamaremos rigido.m
function dy = rigido(t,y)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = -y(1) * y(3);
dy(3) = -0.51 * y(1) * y(2);
Obtenemos la gráfica
Un ejemplo de un problema basado en matrices para ingeniería de análisis de la
contaminación en diferentes zonas urbanas
En una ciudad, se realizó un estudio para medir los niveles de contaminación en varias
zonas. El estudio midió la concentración de contaminantes (PM2.5, CO2 y NO2) en tres
zonas diferentes de la ciudad (Zona 1, Zona 2 y Zona 3). Los resultados fueron los
siguientes:
Concentración de contaminantes (en µg/m³):
Zona 1: PM2.5 = 35 µg/m³, CO2 = 250 µg/m³, NO2 = 45 µg/m³
Zona 2: PM2.5 = 50 µg/m³, CO2 = 300 µg/m³, NO2 = 60 µg/m³
Zona 3: PM2.5 = 25 µg/m³, CO2 = 200 µg/m³, NO2 = 30 µg/m³
A= 25 500 30
50 500 40
75 550 45
B= (0.50.30.2)
35×0.5+400×0.3+50×0.2=17.5+120+10=147.5
=30×0.5+420×0.3+60×0.2=15+126+12=153
=25×0.5+450×0.3+70×0.2=12.5+135+14=161.5
C=A×B
147.5
C= 153
161.5
CONCLUSIONES
Por lo tanto, las matrices son herramientas esenciales que ayudan a los investigadores
y responsables políticos a comprender y gestionar los desafíos ambientales mediante
una representación numérica precisa y la capacidad de resolver sistemas de ecuaciones
que modelan interacciones complejas.
References
[1] Bank, R. E., W. C. Coughran, Jr., W. Fichtner, E. Grosse, D. Rose, and R. Smith,
"Transient Simulation of Silicon Devices and Circuits," IEEE Trans. CAD, 4 (1985), pp
436-451.
[2] Bogacki, P. and L. F. Shampine, "A 3(2) pair of Runge-Kutta formulas," Appl.
Math. Letters, Vol. 2, 1989, pp 1-9.
[5] Kahaner, D. , C. Moler, and S. Nash, Numerical Methods and Software, Prentice-Hall,
New Jersey, 1989.
[9] Shampine, L. F. and M. W. Reichelt, "The MATLAB ODE Suite," SIAM Journal
on Scientific Computing, Vol. 18, 1997, pp 1-22.
[10] Shampine, L. F., M. W. Reichelt, and J.A. Kierzenka, "Solving Index-1 DAEs in
MATLAB and Simulink," SIAM Review, Vol. 41, 1999, pp 538-552.
nzmax odefile
View publication stats