You are on page 1of 59

Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V.

- 467 -

Contenido
CAPITULO 6 ÁLGEBRA LINEAL NUMÉRICA .......................................................... 468
6.1 INTRODUCCION ................................................................................................ 468
6.2. INTERPOLACION POLINOMIAL....................................................................... 468
Interpolación lineal................................................................................................. 468
b) Formula de interpolación de Lagrange .............................................................. 469
6.3. AJUSTE DE CURVAS ....................................................................................... 472
6.3.1 Regresión Lineal ........................................................................................... 472
6.3.2. Otras Regresiones ( poner las 4 regresiones y con ecuacion ..................... 474
6.4 VALOR NUMERICO DE UN POLINOMIO .......................................................... 475
Ejercicio 2 obtener los valores de un polinomio (x+2)(x-1)(x-3) =x3-2x2-5x+6 .... 476
Ejercicio 3. Obtener las raíces del polinomio ......................................................... 477
Área bajo la curva de un polinomio .......................................................................... 478
6.5 SOLUCION DE “N” ECUACIONES CON “M” INCOGNITAS .............................. 479
6.5.1. Eliminación de Gauss Jordan para problemas ideales sencillos ................ 479
6.5.3.Solución de “n” ecuaciones con “m” incógnitas. ........................................... 480
6.6 SOLUCION DE ECUACIONES CON EXCEL ..................................................... 480
6.7 PROBLEMAS RESUELTOS ............................................................................... 481
P601. Eliminación de Gauss ................................................................................. 481
P603 juego de luces ......................................................................................... 485
6.8 AUTOMATA CELULAR ...................................................................................... 486
AUTOMATAS CELULARES DE UNA DIMENSION .............................................. 486
AUTOMATAS CELULARES EN DOS DIMENSIONES ......................................... 489
JUEGO DE LA VIDA DE CONWY EN REJILLA ACOTADA MODO DOS ......... Error!
Bookmark not defined.
P606 .Usando un autómata celular Detectar bordes ............................................ 498
PC07. Rellenar una figura usando autómatas celulares ........................................ 494
6.9 COMPUTACION UNIVERSAL ........................................................................... 505
6.10 EJERCICIOS RESUELTOS ............................................................................ 511
PC608 . Eencontrar el primer elemento del vector B que no este en A y que
elemento es ........................................................................................................... 511
C609 Se ingresan las 4 coordendas de un cuadrilatero encontrar el diagonal .... 512
C610 se ingresan centro x , centro y e radio de n circulos ................................... 514
6.11 PROBLEMAS PROPUESTOS ......................................................................... 515
6.12 OTROS ............................................................................................................. 516
Girar una figura...................................................................................................... 516
DIAGRAMA DE VORONOI Usado en geometria social ....................................... 517
CABLE mejorado ................................................................................................... 519
Determinar si se cruzan o no lineas ...................................................................... 523
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 468 -
CAPITULO 6 ÁLGEBRA LINEAL NUMÉRICA

6.1 INTRODUCCION

El álgebra lineal numérica es fundamental, tanto para el análisis científico como para
los métodos numéricos, por ejemplo para estudiar los métodos computacionales básicos
para resolver conjuntos no homogéneos de ecuaciones lineales1

6.2. INTERPOLACION POLINOMIAL

Una función de interpolación es aquella que pasa a través de puntos dados como datos,
las cuales se muestran comúnmente por medio de tabla de valores o se toman
directamente de una función dada.

La Interpolación polinomial (Ajustar un polinomio a los puntos dados) es uno de los


temas más importantes en métodos numéricos, ya que la mayoría de los modelos se
basan en la interpolación polinomial.

Interpolación lineal

Da como resultado a una recta que se ajusta a dos puntos y esta dado por
b-x x-a 2-1.5 1.5-1
f(x) = ------ f(a) + -------f(b) g(1.5) = ------ (2) + ------- ( 4) == g(x)= 3
b-a b-a 2-1 2-1

donde f(a) y f(b) son valores conocidos de f(x) en x=a i x =b respectivamente


se tiene los siguientes valores f(x)
y
x f(x)
1 1 X f(x) f(x)
1.5 ? A f(a) f(b)
2 4
X f(x)
B f(b) f(a)
Otra forma
a/b=c/d (x-a)/(b-a)= (f(x)-f(a))/(f(b)-f(a))
f(x)=f(a)+ (x-a)/(b-a)* (f(b)-f(a))
f(x)= =1+((1.5-1)/(2-1)*(4-1))=2.5 a b x
Elaborar una función para realizar ello

Module module1
Function g(ByVal x As Single, ByVal a As Single, ByVal b As Single, ByVal fa As
Single, ByVal fb As Single) As Single
Return fa + (x - a) / (b - a) * (fb - fa) REM return (b-x)/(b-a)*fa+(x-a)/(b-a)*fb
End Function
Sub main()
Dim a As Single = 1, b As Single = 2, fa As Single = 1, fb As Single = 4, x As Single =
1.5
Console.WriteLine(" valor interpolado {0} ", g(x, a, b, fa, fb))
Console.ReadLine()
End Sub

1
Nakamura Shoichero / Métodos numéricos aplicados con software Pag.. 184
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 469 -
End Module

b) Formula de interpolación de Lagrange

Pueden ajustarse tres o cuatro datos por medio de una curva. Uno de los métodos para
encontrar una función que pasa a traves de datos dados es el de usar un polinomio

Fórmula
(x-x1)(x-x2) ... (x-xN) f3
g(x) = ------------------------------ f0 y f1 f2
(x0-x1)(x0-x2) ... (x0-xN) f0
(x-x0)(x-x2) ... (x-xN)
+ ------------------------------ f1
(x1-x0)(x1-x2) ... (x1-xN)
x0 x1 x2 x3 x
. (x-x0)(x-x1 ... (x-xN-1)
+ ------------------------------ fN
(xN-x0)(xN-x2) ... (xN-xN-1)

a) las densidades de sodio para tres temperaturas están dados como sigue
I Temperatura(Ti) densidad Pi
0 94 ° C 929 Kg/cm2
1 205 902
2 371 860
Escriba la fórmula de Interpolación de Lagrange que se ajusta a los tres datos
b) Determine la densidad para T=251°C utilizando la interpolación de Lagrange
Solución
a) Ya que el Numero de datos es tres el orden de la fórmula de Lagrange es N=2 , La
interpolación de Lagrange queda
(T-205)(T-371) .
g(T) = ------------------------ (929)
(94-205)(94-371) .

(T-94)(T-371)
+ -------------------------(902)
(205-94)(205-371)

. (T-94)(T-205 ...
+ ----------------------- (860)-
(371-94)(371-205) ... )

b) Sustituyendo T= 251 en la ecuación anterior obtenemos g(251)= 890.5 Kg/cm2

Programa es molesto hacerlo manualmente y se incrementa la posibilidad de cometer


errores
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 470 -
Module module1
Sub main()
Const max As Integer = 10
Dim nd As Integer = 2
Dim X() As Single = {94, 205, 371}
Dim F() As Single = {929, 902, 860}
ReDim Preserve X(max)
ReDim Preserve F(max)
Dim xa As Single = 251 REM valor a interpolar
Console.WriteLine(" interpolacion con 3 puntos para x={0} es {1} ", xa,
interpolar(X, F, nd, xa))
console.readline()
End Sub
Function interpolar(ByVal X() As Single, ByVal F() As Single, ByVal n As Integer,
ByVal xa As Single) As Single
Dim g As Single = 0, z As Single, i As Integer, j As Integer
For i = 0 To n - 1
z = F(i)
For j = 0 To n - 1
If (i <> j) Then
z = z * (xa - X(j)) / (X(i) - X(j))
g=g+z
End If
Next
Next 10
Return g 9
8
End Function 7
End Module 6
5
4
Interpolar los puntos intermedios 3
2
1
0 x
Punto X y1
-1 0 5 10 15 20 25 30 35 40 45 50
0 0 0 -2 est
-3
1 5 -10 -4
2 10 -6 -5
-6
3 15 6 -7
4 20 9 -8
-9
5 25 -2 -10
-11
6 30 -10
7 35 -5
8 40 7
9 45 8
est 1 11 -3.887
est 2 12 -1.455
est 3 13 1.133
est 4 14 3.68
est 5 15 6
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 471 -

Imports System.IO
Module module1
Sub main()
Const max As Integer = 12
Dim np As Integer = 10
Dim X(max) As Single
Dim F(max) As Single
Dim A(max, max) As Single
RecuperarMatriz("E:\datos\puntos10.txt", A, np, 2)
MatrizXYZ(A, np, X, F)
Mostrar(X, F, np)
Dim xa As Single = 14 REM valor a interpolar
Console.WriteLine(" interpolacion con {0} puntos para xa={1} es {2} ", np, xa,
interpolar(X, F, np - 1, xa))
Console.ReadLine()
End Sub

Sub MatrizXYZ(ByVal A(,) As Single, ByVal nf As Integer, ByRef X() As Single, ByRef
Y() As Single)
For fila = 0 To nf
X(fila) = A(fila, 0)
Y(fila) = A(fila, 1)
Next
End Sub
Sub Mostrar(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer)
Dim i As Integer
For i = 0 To np - 1
Console.WriteLine(" {0} {1} {2} ", i, X(i), Y(i))
Next
End Sub
Function interpolar(ByVal X() As Single, ByVal F() As Single, ByVal n As Integer,
ByVal xa As Single) As Double
Dim g As Single = 0, z As Single, i As Integer, j As Integer
For i = 0 To n - 1
z = F(i)
For j = 0 To n - 1
If (i <> j) Then
z = z * (xa - X(j)) / (X(i) - X(j))
g=g+z
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 472 -
End If
Next
Next
Return g
End Function
Ver en archivos
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Single, ByVal nf
As Integer, ByVal nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
For fila = 0 To nf - 1
cadena = srLector.ReadLine()
cadena = cadena & Chr(9)
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = CSng(Val(subcadena))
inicio = pos + 1
Next
Next
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
End Module

6.3. AJUSTE DE CURVAS

Los datos que se obtienen de mediciones fluctúan, esto se debe a errores aleatorios de
sistema de medición aplicado al comportamiento intrínsicamente estocástico del
sistema en observación. Cualquiera se la razón, es frecuente que surja la necesidad de
ajustar una función a los datos de una medición .

Si el número de datos es igual al orden de un polinomio más uno, podemos ajustar con
exactitud dicho polinomio a los datos. Sin embargo, al hacer el ajuste de una función a
los datos de una medición, deben utilizarse un número de datos mucho mayor que el
orden del polinomio. De hecho mientras mas datos se utilicen , mejor será la precisión
de la curva ajustada.

6.3.1 Regresión Lineal

La ecuación de la recta es y= a+ b(x) y los valores de ay b se obtienen de

a= y/n+Bx/n y b=(nxy-xy)/(nx2-(x)2.

El coeficiente de correlación para el modelo lineal es


r = (nXY-xy)./( ((nx2-(x)2)*  (ny2-(y)2 )
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 473 -

2
x y x*y X Y2 135
130 y = 4.7x + 103.7
1 108 108 1 11664 125
120
2 119 238 4 14161 115
110
3 110 330 9 12100 105
4 122 488 16 14884 100 R² = 0.6801
95
5 130 650 25 16900 90
85
Suma 15 589 1814 55 69709 80
0 2 4 6
Calculo de b=(nxy-xy)/(nx2-(x)2.

b= (5*1814-15*589)/(5*55-15*15)= 235/50 = 4.7


a= y/n-Bx/n = 589/5- 4.7(15/5) = 103.7

r= (nXY-xy)./( ((nx2-(x)2)*  (ny2-(y)2 )

r= (5*1814-15*589)/  (5(55)-15*15)  (5(69709)-(589)2 )


r= 235/ 501624= 235/284.956137 = 0.824688
r2 = 0.6801

Programa para regresión lineal

Module module1
Sub main()
Const max As Integer = 10
Dim n As Integer = 5, i As Integer
Dim x() As Single = {1, 2, 3, 4, 5}
Dim y() As Single = {108, 119, 110, 122, 130}
ReDim Preserve x(max)
ReDim Preserve y(max)
Dim a As Single, b As Single, sx As Single = 0
Dim sy As Single = 0, sxy As Single = 0, sx2 As Single = 0, sy2 As Single = 0, r As
Single
For i = 0 To n
sx = sx + x(i)
sy = sy + y(i)
sxy = sxy + x(i) * y(i)
sx2 = sx2 + x(i) * x(i)
sy2 = sy2 + y(i) * y(i)
b = (n * sxy - sx * sy) / (n * sx2 - sx * sx)
a = (sy - b * sx) / n
r = CSng((n * sxy - sx * sy) / (Math.Sqrt(n * sx2 - sx * sx) * Math.Sqrt(n * sy2 - sy *
sy)))
Next
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 474 -
Console.WriteLine(" La recta es Y= {0} + {1} x ", a, b)
Console.WriteLine(" Coefeciente de correlacion = {0}", r)
Console.ReadLine()
End Sub
End Module

6.3.2. Otras Regresiones ( poner las 4 regresiones y con ecuacion


Despues de jordan gauss

Para otras regresiones como Parabólica, exponencial, etc se Puede usar Microsoft
Excel
Nota. El Microsoft Excel proporciona gráfica que nos permiten obtener las regresiones
para una serie de datos por los métodos
Lineal logarítmica Polinomial ( de 2 a 6)
Potencia Exponencial Media móvil
Para ello utilice el Asistente para gráficos, una vez graficado los datos, haga clic en la
serie de datos y luego escoger la opción agregar línea de tendencia

Método de regresión exponencial de pronósticos( o modelo logaritmico) y = abx

a= ((log(y))- log(b)x )/n


b= (nlog(y)*x-xlog(y)/((nx2-(x)2.
r= (nlog(y)*x-xlog(y) / ./( ((nx2-(x)2)* (n(log y)2-(log y)2 )

2
x y log(y) log(y)*x x log(y)*log(y)
1 108 2.0334 2.0334 1 4.1348
2 119 2.0755 4.1511 4 4.3079
3 110 2.0414 6.1242 9 4.1673
4 122 2.0864 8.3454 16 4.3529
5 130 2.1139 10.5697 25 4.4688
sumas 15 589 10.3507 31.2239 55 21.4316

log(b)= (5(31.2239)-15*(10.3507)/(5*55)-15*15)
log(b)= 0.8590 /50 = 0.0172
log(a)= ((10.3507)- 0.0172(15))/5 =2.0185 log(b) = 2.0185
a= antilog(2.0185)= 104.3518
b= antilog(0.0172)= 1.0404

Module module1
Sub main()
Const max As Integer = 10
Dim n As Integer = 5, i As Integer
Dim x() As Single = {1, 2, 3, 4, 5}
Dim y() As Single = {108, 119, 110, 122, 130}
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 475 -
ReDim Preserve x(max)
ReDim Preserve y(max)
Dim a As Single, b As Single, sx As Single = 0, ly As Single
Dim a1 As Single, b1 As Single

Dim sly As Single = 0, sxly As Single = 0


Dim sx2 As Single = 0, sly2 As Single = 0, r As Single
For i = 0 To n - 1
sx = sx + x(i)
ly = CSng(Math.Log10(y(i)))
sly = sly + ly
sxly = sxly + x(i) * ly
sx2 = sx2 + x(i) * x(i)
sly2 = sly2 + ly * ly
Next
b = (n * sxly - sx * sly) / (n * sx2 - sx * sx)
a = (sly - b * sx) / n
r = CSng((n * sxly - sx * sly) / (Math.Sqrt(n * sx2 - sx * sx) * Math.Sqrt(n * sly2 - sly *
sly)))
b1 = CSng(Math.Pow(10, b))
a1 = CSng(Math.Pow(10, a))
Console.WriteLine(" La curva es Y= {0} + {1} elevado a x ", a1, b1)
Console.WriteLine(" Coefeciente de correlacion = {0}", r)
Console.ReadLine()
End Sub
End Module

Tarea Elaborar una aplicacion para el modelo parabólico

Ecuaciones para el cálculo de líneas de tendencia en Excel


Vea en la ayuda de Microsoft Excel Busque ecuaciones para el cálculo de linea de
tendencia

6.4 VALOR NUMERICO DE UN POLINOMIO

Valor numérico de un polinomio.-Escribir un programa que utilice una función para


calcular el valor numérico de un polinomio

Module module1
Const max As Integer = 10
Function vn(ByVal p() As Single, ByVal g As Integer, ByVal x As Single) As Single
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 476 -
Dim v As Single = 0, i As Integer
For i = g To 0 Step -1
v = v * x + p(i)
Next
Return v
End Function

Sub main()
Dim n, i As Integer
Dim poli(max), x, dato, r As Single
Console.WriteLine(" Grado :")
n = CInt(Console.ReadLine())
Console.Write(" {0} coefecientes a partir de grado mayor", n + 1)
For i = n To 0 Step -1
dato = CSng(Console.ReadLine())
poli(i) = dato
Next
Console.Write(" Ingrese el valor de x")
x = CSng(Console.ReadLine())
r = vn(poli, n, x)
Console.WriteLine(" valor numerico de polinomio {0} ", r)
Console.ReadLine()
End Sub
End Module

El polinomio es x5+2x2-3x3+0x2+2x+1

Ejercicio 2 obtener los valores de un polinomio (x+2)(x-1)(x-3) =x3-2x2-5x+6

=X3-2X2+3X-5

Module module1
Const max As Integer = 10
Function vn(ByVal p() As Single, ByVal g As Integer, ByVal x As Single) As Single
Dim v As Single = 0, i As Integer
For i = g To 0 Step -1
v = v * x + p(i)
Next
Return v
End Function
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 477 -

Sub main()
Dim n, i, nd As Integer
Dim poli(max), x, dato, r As Single
Dim a, b, dx As Single
Console.Write(" Grado :")
n = CInt(Console.ReadLine())
Console.Write("{0} coefecientes a partir de grado mayor", n + 1)
For i = n To 0 Step -1
dato = CSng(Console.ReadLine())
poli(i) = dato
Next
Console.Write(" Ingrese limite a ")
a = CSng(Console.ReadLine())
Console.Write(" Ingrese limite b ")
b = CSng(Console.ReadLine())
Console.Write(" Ingrese numero de divisiones n ")
nd = CInt(Console.ReadLine())
dx = (b - a) / nd
For x = a To b - dx Step dx
r = vn(poli, n, x)
Console.WriteLine(" {0,8:f2} {1,8:f2} ", x, r)
Next
Console.ReadLine()
End Sub
nd Module

Ejercicio 3. Obtener las raíces del polinomio

Module module1
Const max As Integer = 10
Function vn(ByVal p() As Single, ByVal g As Integer, ByVal x As Single) As Single
Dim v As Single = 0, i As Integer
For i = g To 0 Step -1
v = v * x + p(i)
Next
Return v
End Function
Sub buscartodas(ByVal poli() As Single, ByVal n As Integer, ByVal a As Single, _
ByVal b As Single, ByVal h As Single) REM puede retornar un vector
Dim x, x1, y1, y2 As Single
x=a
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 478 -
x1 = x + h
While (x1 <= b)
y1 = vn(poli, n, x)
y2 = vn(poli, n, x1)
If (y1 * y2 < 0) Then
Console.WriteLine(" raiz esta en {0} y {1} ", x, x1)
End If
x = x1
x1 = x + h
End While
End Sub
Sub main()
Dim n, i As Integer
Dim poli(max) As Single, x As Single, dato As Single, r As Single
Dim a, b, h As Single
Console.Write(" Grado :")
n = CInt(Console.ReadLine())
Console.Write(" {0} coefecientes a partir de grado mayor", n + 1)
For i = n To 0 Step -1
dato = CSng(Console.ReadLine())
poli(i) = dato
Next
Console.Write(" Ingrese limite a ")
a = CSng(Console.ReadLine())
Console.Write(" Ingrese limite b ")
b = CSng(Console.ReadLine())
Console.Write(" Ingrese h ")
h = CSng(Console.ReadLine())
buscartodas(poli, n, a, b, h)
Console.ReadLine()
End Sub
End Module

Área bajo la curva de un polinomio

Module module1
Const max As Integer = 10
Function vn(ByVal p() As Single, ByVal g As Integer, ByVal x As Single) As Single
Dim v As Single = 0, i As Integer
For i = g To 0 Step -1
v = v * x + p(i)
Next
Return v
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 479 -
End Function

Function trapecial(ByVal poli() As Single, ByVal n As Integer, ByVal a As Single,


ByVal b As Single, ByVal nd As Integer) As Single
Dim at As Single = 0
Dim ap, dx, x, x1, y1, y2 As Single
dx = (b - a) / nd
For x = a To b Step dx
x1 = x + dx
y1 = vn(poli, n, x)
y2 = vn(poli, n, x1)
ap = (y1 + y2) / 2 * dx
at = at + ap
Next
Return at
End Function

Sub main()
Dim n, i, nd As Integer
Dim poli(max) As Single, x As Single, dato As Single, r As Single
Dim a, b, h As Single
Console.Write(" Grado :")
n = CInt(Console.ReadLine())
Console.Write(" {0} coefecientes a partir de grado mayor", n + 1)
For i = n To 0 Step -1
dato = CSng(Console.ReadLine())
poli(i) = dato
Next
Console.Write(" Ingrese limite a ")
a = CSng(Console.ReadLine())
Console.Write(" Ingrese limite b ")
b = CSng(Console.ReadLine())
Console.Write(" Ingrese numero de divisiones")
nd = CInt(Console.ReadLine())
Console.WriteLine(" el area por el metodo trapecial es {0}", trapecial(poli, n, a, b, nd))
Console.ReadLine()
End Sub
End Module

6.5 SOLUCION DE “N” ECUACIONES CON “M” INCOGNITAS

6.5.1. Eliminación de Gauss Jordan para problemas ideales sencillos2

La eliminación de Gauss es el método que se utiliza en forma más amplia para resolver
un conjunto de ecuaciones lineales
Resuelva las siguientes ecuaciones mediante la eliminación de Gauss con el cálculo
manual.
- 0.04x1+ 0.04x2 + 0.12X3 = 3
- 0.56x1 – 1.56x2 + 0.32X3 = 1
- 0.24x1+ 0.24x2 - 0.28X3 = 0
Solución
2
Nakamuara Op.Cit Pág.. 185.
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 480 -
El arreglo del problema es:
- 0.04 0.04 0.12 3
0.56 -1.56 0.32 1
- 0.24 0.24 -0.28 0

La eliminación hacia adelante es como sigue


renglón 1 - 0.04 0.04 0.12 3
renglón 2 0.56 -1.56 0.32 1
renglón 3 - 0.24 0.24 -0.28 0

renglón 1 por 0.56/(0.04)=14: 0.04 0.04 0.12 3 (A)


renglón 1 por 0.24/(0.04)= 6 : 0.56 -1.56 0.32 1 (B)

Sumamos (A) al renglón 2 , restamos (B) del renglón 3 para obtener:


renglón 1 - 0.04 0.04 0.12 3
renglón 2 0.00 -1.00 2.00 43
renglón 3 - 0.24 1.00 -1.00 -18

El segundo coeficiente del tercer renglón se elimina sumando el renglón 2 con el renglón
3.
renglón 1 - 0.04 0.04 0.12 3
renglón 2 0.00 - 1.00 2.00 43
renglón 3 - 0.24 0.00 1.00 25
Las sustituciones hacia atrás de la eliminación de Gauss son directas
x1 = 25/(1) = 25
x2 = [ (43 - (2)(25) ]/ ( -1) = 7
x3 = [3 – (0.12) (25) – (0.04)(7) ] / (-0.04) = 7

6.5.2 Pivoteo y eliminación canónica de Gauss

En la sección 6.4.1 la eliminación de Gauss se aplica a un problema ideal sencillo con


coeficientes no nulos. Sin embargo el método no funciona si el primer coeficiente del
primer renglón es cero o si un coeficiente de la diagonal se anula en el proceso de
solución, ya que se usa como denominadores en la eliminación hacia delante. Para
mayor detalla vea el libro de Nakamura3, el programa C601 resuelve este caso.

6.5.3.Solución de “n” ecuaciones con “m” incógnitas.


Se sugiere al alumno que estudie Nakamura Capítulo 6 Págs 185 al 232 y convierta a
C++ el programa de la página 231.

6.6 SOLUCION DE ECUACIONES CON EXCEL

Resolviendo ecuaciones simultaneas Use funciones MINVERSA Y MMMULT

3
Ibid Pág. 191 a 194
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 481 -

Celda A8: {=MINVERSA(A5:B6)}


Celda b11={ =MMULT(A8:B9,C5:C6)}
Ecuaciones simultaneas con 3 variables

6.7 PROBLEMAS RESUELTOS

P601. Eliminación de Gauss .Este problema resuelve un conjunto de ecuaciones


lineales por el método de Gauss con pivote , de acuerdo con el algoritmo de la
sección 4.6.2. Este programa ha sido convertido y modificado del Código fuente
hecha en ForTran ( si ya esta hecho ya no hacerlo)
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 482 -

Module Module1
Sub main()
RecuperarMatriz(NombreArchivo, a, nfilas, ncol)
Console.WriteLine(" matriz aumentada")
MostrarMatriz(A, nfilas, ncol)
gauss(A, nfilas)
Console.WriteLine(" {0,8} {1,8} ", "x", "x(i)")
For i = 0 To nfilas - 1
Console.WriteLine(" {0,8:f4} {1,8:f4}", i, A(i, nfilas))
Next
Console.ReadLine()
End Sub
End Module

Imports System.IO
Module Module2
Public Const maxfilas As Integer = 10
Public Const maxcol As Integer = 10
Public A(maxfilas, maxcol) As Single
Public nf As Integer = 2
Public nc As Integer = 3
Public NombreArchivo As String = "c:\datos\ECUA2X2.txt"
Public nfilas, ncol As Integer
Function ContarLetra(Cadena As String, letra As Char)
Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant
End Function
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Single, ByRef nf
As Integer, ByRef nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab) + 1
Do While Not (cadena = "")
cadena = cadena & vbTab
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 483 -
A(fila, col) = Val(subcadena)
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
Sub MostrarMatriz(A(,) As Single, nf As Integer, nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Console.Write("{0} {1}", A(fila, col), vbTab)
Next
Console.WriteLine()
Next
End Sub
Sub gauss(ByVal a(,) As Single, ByVal n As Integer) REM nro de filas
Dim i As Integer, j As Integer
Dim k As Integer, PV As Integer, jc As Integer
Dim jr As Integer, kc As Integer, nv As Integer
Dim eps As Single = 1
Dim eps2 As Single
Dim det As Single, temp As Single, r As Single, va As Single, tm As Single
While (1 + eps > 1)
eps = CSng(eps / 2.0)
End While
eps = CSng(eps * 2.0)
Console.WriteLine()
Console.Write("Epsilon de la maquina {0} ", eps)
eps2 = eps * 2
det = 1
For i = 0 To n - 2
REM puede ser i=1 i<=n-1
PV = i
For j = i + 1 To n - 1
If Math.Abs(a(PV, i)) < Math.Abs(a(j, i)) Then PV = j
Next j
If (PV <> i) Then
For jc = 0 To n
tm = a(i, jc)
a(i, jc) = a(PV, jc)
a(PV, jc) = tm
Next jc
det = -1 * det
End If

' cada vez que se realiza un pivoteo , cambia el signo de det


If (a(i, i) = 0) Then REM la matriz es singular
Console.WriteLine(" la matriz es singular")
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 484 -
Exit Sub
REM Return 0
End If
For jr = i + 1 To n - 1
If (a(jr, i) <> 0) Then
r = a(jr, i) / a(i, i)
For kc = i + 1 To n
temp = a(jr, kc)
a(jr, kc) = a(jr, kc) - r * a(i, kc)
If Math.Abs(a(jr, kc)) < eps2 * temp Then a(jr, kc) = 0.0
Next kc
End If
Next jr
Next i
' fin del for jr externo
For i = 0 To n - 1
det = det * a(i, i)
Next
Console.WriteLine()
Console.WriteLine(" determinante {0} ", det)
'If (a(n, n) = 0) Then
' Console.Write("\n la matriz es singular")
' Exit Sub
'End If
a(n - 1, n) = a(n - 1, n) / a(n - 1, n - 1)
For nv = n - 2 To 0 Step -1
REM arreglado hasta aqui 1
va = a(nv, n) ' arreglo
For k = nv + 1 To n - 1
va = va - a(nv, k) * a(k, n)
Next k
a(nv, n) = va / a(nv, nv)
Next nv
End Sub
End Module

Segunda corrida
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 485 -
Dado 3 puntos encuentre la ecuacion de la circunferencia y grafique

P603 juego de luces Se tiene leds de forma cuadrada prender y apagar las luces
en forma aleatoria

Module Module1
Const mfilas As Integer = 10, mcol As Integer = 10
Sub cuadro(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila As Integer, col As Integer
For fila = 0 To alto - 1
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
Next
Next
End Sub
Sub main()
Dim nf As Integer = 4, nc As Integer = 5, cx As Integer = 10, cy As Integer = 2, rx
As Integer, ry As Integer
Dim C(mfilas, mcol) As Integer
IniciarMatriz(C, nf, nc)
mostrarMatriz(cx, cy, C, nf, nc)
While CBool((1))
rx = CInt(Rnd() * (nc - 1))
ry = CInt(Rnd() * (nf - 1))
If (C(ry, rx) < 8) Then
C(ry, rx) = C(ry, rx) + 8
Else : C(ry, rx) = C(ry, rx) - 8
End If
Console.BackgroundColor = CType(C(ry, rx), ConsoleColor)

Console.ForegroundColor = CType(C(ry, rx), ConsoleColor)


cuadro(cx + rx * 8, cy + ry * 5, 8 - 1, 5 - 1)
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 486 -
Console.Beep(37 + 10 * rx * ry, 100)
End While
Console.ReadLine()
End Sub

Sub IniciarMatriz(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer)


Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
A(fila, col) = CInt(1 + Rnd() * 7)
Next
Next
End Sub

Sub mostrarMatriz(ByVal cx As Integer, ByVal cy As Integer, ByVal A(,) As Integer,


ByVal nf As Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Console.BackgroundColor = CType(A(fila, col), ConsoleColor)
Console.ForegroundColor = CType(A(fila, col), ConsoleColor)
cuadro(cx + col * 8, cy + fila * 5, 8 - 1, 5 - 1)
Next
Next
End Sub
End Module

6.8 AUTOMATA CELULAR

Los automátas celulares son herramientas útiles para modelar cualquier sistema en el
universo. Pueden considerarse como una buena alternativa a las ecuaciones
diferenciales y han sido utilizados para modelar sistemas físicos, como interacciones
entre partículas, formación de galaxias, cinética de sistemas moleculares y crecimiento
de cristales, asi como diversos sistemas biológicos a nivel celular, multicelular y
poblacional.

AUTOMATAS CELULARES DE UNA DIMENSION

El AC no trivial más simple consiste en una retícula unidimensional de células que sólo
pueden tener dos estados (« 0 » o « 1 »), con un vecindario constituido, para cada
célula, de ella misma y de las dos células adyacentes (23=8 configuraciones posibles).
Existen 28=256 modos de definir cuál ha de ser el estado de una célula en la
generación siguiente para cada una de estas configuraciones, luego existen 256 AC
diferentes de este tipo.
Consideremos el AC definido por la tabla siguiente, que nos da la regla de evolución:
Motivo inicial 111 110 101 100 011 010 001 000
Valor siguiente de la célula central 0 0 0 1 1 1 1 0

un autómata celular unidimensional consiste en una sucesión o secuencia de sitios


(una configuración o estado) donde cada sitio o celda contiene un valor numérico, y los
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 487 -
valores de los sitios evolucionan en pasos de tiempo discretos según reglas
determinísticas.

Reglas hay 256 reglas

Aplicando la regla 72

128 64 32 16 8 4 2 1 72
0 1 0 0 1 0 0 0

Imports System.IO
Module Module1
Const ne As Integer = 8, nfilas As Integer = 25
Dim ncol As Integer = 80
Sub main()
Dim fila As Integer, col As Integer, nf As Integer = 24
Dim nc As Integer = 60, resultado As Integer = 0
Dim k As Integer
Dim R(nfilas, ncol), V(3) As Integer
Dim A(ne, 3) As Integer
RecuperarMatriz("e:\datos\auto3x8.txt", a, ne, 3)
mostrarMatriz(1, 1, R, nf, nc)
Dim VR() As Integer = {0, 1, 0, 0, 1, 0, 0, 0}
ReDim Preserve VR(ne)
IniciarMatriz(R, nf, nc)
R(0, 30) = 1
REM sacar de 3 en 3
For k = 0 To nf - 1
For col = 1 To nc - 2
V(0) = R(k, col - 1)
V(1) = R(k, col)
V(2) = R(k, col + 1)
REM genera solucion de acuerdo al patron
For fila = 0 To ne
If (V(0) = A(fila, 0) And V(1) = A(fila, 1) And V(2) = A(fila, 2)) Then
resultado = fila
Exit For
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 488 -
End If
Next
R(k + 1, col) = VR(resultado)
Next
Next
mostrarMatriz(1, 1, R, nf, nc)
Console.ReadLine()
End Sub

Sub IniciarMatriz(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer)


Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
A(fila, col) = 0
Next
Next
End Sub

Sub mostrarMatriz(ByVal cx As Integer, ByVal cy As Integer, ByVal A(,) As Integer,


ByVal nf As Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Console.BackgroundColor = CType(A(fila, col), ConsoleColor)
Console.ForegroundColor = CType(A(fila, col), ConsoleColor)
Console.SetCursorPosition(cx + col, cy + fila)
If (A(fila, col) > 0) Then
Console.Write("*")
End If
Next
Next
End Sub

Sub RecuperarMatriz(ByVal nombrearchivo As String, ByVal A(,) As Integer, ByVal nf


As Integer, ByVal nc As Integer)
Dim srlector As StreamReader
srlector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
For fila = 0 To nf - 1
cadena = srlector.ReadLine()
cadena = cadena & Chr(9)
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = CInt(CSng(Val(subcadena)))
inicio = pos + 1
Next
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 489 -
Next
srlector.Close()
End Sub
End Module

Modifique la salida y vera (regla 126)


Dim VR() As Integer = {0, 1, 1, 1, 1, 1, 1, 0}

Dim VR() As Integer = {0, 1, 0, 1, 1, 0, 1, 0} REM regla 90


Dim VR() As Integer = {0, 1, 0, 0, 1, 0, 0, 0} ' regla 50

AUTOMATAS CELULARES EN DOS DIMENSIONES

PC605. Simulación del juego de la vida de Conway en una rejilla acotada


(inventado por el Británico J.C. CONWAY en 1970).
1. Reglas del juego de la vida:
La estructura del juego que en realidad es una simulaciones una rejilla rectangular
abierta, en la cual cada celdilla puede estar ocupada o no por un microorganismo. las
celdillas vivas cambian de una generación a otra, según el número de celdillas vecinas
que están vivas, en la forma siguiente:
a) Los vecinos de una celda son los ocho que la tocan vertical, horizontal o
diagonalmente.
b) Si una celdilla está viva pero no tiene celdillas vecinas que estan vivas, muere de
soledad en la siguiente generación.
c) Si una celdilla está viva y tiene cuatro o más vecinas tambien vivas, en la siguiente
generación muere por hacinamiento.
d) Una celdilla viva con dos o tres vecinas vivas permanece viva en la siguiente
generación.
e) Si una celdilla esta muerta, en la siguiente generación recuperará la vida, si tiene
exactamente tres vecinas, ni una más ni uno menos, que ya estan vivas. Todas las
otras celdillas muertas permanecen as¡ en la siguiente generación.
f) Todos los nacimientos y muertes tienen lugar exactamente al mismo tiempo, de
manera que las que mueren ayudan a producir otras; pero no pueden evitar la muerte
de otras reduciendo el hacinamiento, ni las que nacen pueden preservar o destruir a
las que tienen vida en la generación anterior.
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 490 -
A continuación se muestra con una secuencia de pasos lo que sucede con deslizador
conforme vamos pasando de una generación a otra

Diseñar un modelo en Excel y grabar como "E:\\datos\\GOSPER40x20.txt","r";

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Module Module1
Sub MAIN()
Dim i, modo As Integer
RecuperarModelo(NombreArchivo, Modelo, nfilas, ncol)
Console.WriteLine("juego de la vida ")
MostrarMatriz(Modelo, nfilas, ncol)
Console.Write("Modo 0. Modo Manual 1. Automatico === :")
modo = Console.ReadLine
Select Case modo
Case 0
MostrarMatriz(Modelo, nfilas, ncol)
For i = 0 To ng
Console.WriteLine("iter" & i)
JuegoVida(Modelo, nfilas, ncol)
MostrarMatriz(Modelo, nfilas, ncol)
Console.ReadLine()
Next
Case 1
Console.Clear()
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 491 -
VerMatriz(Modelo, cx, cy, nfilas, ncol)
For i = 0 To ng
JuegoVida(Modelo, nfilas, ncol)
VerMatriz(Modelo, cx, cy, nfilas, ncol)
'Console.ReadLine()
System.Threading.Thread.Sleep(10) ' 1 segundo
Next
End Select
Console.ReadLine()
End Sub
End Module

Imports System.IO
Module ModulE2
Public Const maxfilas As Integer = 100
Public Const maxcol As Integer = 100
Public Modelo(maxfilas, maxcol) As Integer
Public cx As Integer = 10
Public cy As Integer = 2

Public nfilas As Integer = 4


Public ncol As Integer = 4
Public ng As Integer = 100
Public NombreArchivo As String = "c:\datos1\gosper40x20.txt"
Sub TranferirMatriz(ByVal A(,) As Integer, ByVal B(,) As Integer, ByVal nf As Integer,
ByVal nc As Integer)
Dim fila, col As Integer
For fila = 1 To nf - 1
For col = 1 To nc - 1
B(fila, col) = A(fila, col)
Next
Next
End Sub
Sub JuegoVida(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer)
Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos, x1, y1, x2, y2, fila1, col1 As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
vecinos = 0
If fila > 1 Then
y1 = fila - 1
Else
y1 = fila
End If
If fila < nf - 1 Then
y2 = fila + 1
Else
y2 = fila
End If
If col > 1 Then
x1 = col - 1
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 492 -
Else
x1 = col
End If
If col < nc Then
x2 = col + 1
Else
x2 = col
End If
For fila1 = y1 To y2
For col1 = x1 To x2
If (fila1 = fila And col1 = col) Then Continue For
If A(fila1, col1) = 1 Then vecinos = vecinos + 1
Next
Next
Select Case vecinos
Case 0, 1 : B(fila, col) = 0
Case 2
B(fila, col) = A(fila, col)
Case 3 : B(fila, col) = 1
Case Else
B(fila, col) = 0
End Select
Next
Next
IniciarPantalla(A, nf, nc, 0)
TranferirMatriz(B, A, nf, nc)
End Sub
Function ContarLetra(Cadena As String, letra As Char)
Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant
End Function
Sub RecuperarModelo(ByVal nombrearchivo As String, ByRef A(,) As Integer,
ByRef nf As Integer, ByRef nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab) + 1
Do While Not (cadena = "")
cadena = cadena & vbTab
inicio = 1
For col = 0 To nc - 1
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 493 -
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = Val(subcadena)
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub

Sub VerMatriz(ByVal A(,) As Integer, cx As Integer, cy As Integer,


ByVal nf As Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
If A(fila, col) <= 15 Then
Console.SetCursorPosition(cx + col, cy + fila)
Select Case A(fila, col)
Case 0 : Console.ForegroundColor = 12
Case 1 : Console.ForegroundColor = 10
End Select
Console.Write("{0}", A(fila, col))
End If
Next
Next
End Sub
Sub IniciarPantalla(A(,) As Integer, nf As Integer, nc As Integer, valor As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
A(fila, col) = valor
Next
Next
End Sub

Sub MostrarMatriz(A(,) As Integer, nf As Integer, nc As Integer)


Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Console.Write("{0} {1}", A(fila, col), vbTab)
Next
Console.WriteLine()
Next
End Sub
End Module

Vea esta regla

Select Case vecinos


Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 494 -
Case 0
B(fila, col) = 0
Case 1
B(fila, col) = 1
Case 2
B(fila, col) = A(fila, col)
Case Else
B(fila, col) = 0
End Select

Pruebe con otros patrones

Select Case vecinos


Case 1
B(fila, col) = 1
Case Else
B(fila, col) = 0
End Select

Usando automata celular para rellenar figuras cerradas en este caso rellena sectores

PC07. Rellenar una figura usando autómatas celulares

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2 0 8 8 8 8 0 0 0 0 0 0 0 0 0 0 0
3 0 8 0 0 8 8 8 8 8 8 8 8 8 8 0 0
4 0 8 0 9 8 0 0 0 0 0 0 0 0 8 0 0
5 0 8 2 9 0 0 0 0 0 8 8 8 0 8 0 0
6 0 8 0 9 0 7 0 0 0 8 0 8 0 8 0 0
7 0 8 0 9 0 7 0 1 0 8 0 8 0 8 0 0
8 0 8 0 9 0 0 0 0 0 8 0 0 0 8 0 0
9 0 8 8 9 9 0 0 0 0 8 8 8 8 8 0 0
10 0 8 0 0 9 8 8 0 0 0 8 0 0 8 0 0
11 0 8 0 0 0 0 8 0 8 8 8 0 0 8 0 0
12 0 8 0 3 0 0 8 0 8 0 8 0 8 8 0 0
13 0 8 8 8 8 0 8 0 0 0 0 0 8 0 0 0
14 0 0 0 0 8 8 8 8 8 8 8 8 8 0 0 0
15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 495 -

Module Module1
Sub MAIN()
Dim I As Integer
RecuperarModelo(NombreArchivo, Modelo, nfilas, ncol)
VerMatriz(Modelo, 10, 2, nfilas, ncol)
For i = 0 To 100
semilla = 1 + Int(Rnd() * 3)
If semilla > 3 Then semilla = 3
JuegoVida(Modelo, nfilas, ncol, semilla)
VerMatriz(Modelo, 10, 2, nfilas, ncol)
Next
Console.ReadLine()
End Sub
End Module

Imports System.IO
Module ModulE2
Public Const maxfilas As Integer = 16
Public Const maxcol As Integer = 16
Public Modelo(maxfilas, maxcol) As Integer
Public cx As Integer = 10
Public cy As Integer = 2
Public semilla As Integer = 2
Public nfilas As Integer = 4
Public ncol As Integer = 4
Public ng As Integer = 20
Public NombreArchivo As String = "c:\datos1\MODELO16X16.txt"
Sub TranferirMatriz(ByVal A(,) As Integer, ByVal B(,) As Integer, ByVal nf As Integer,
ByVal nc As Integer)
Dim fila, col As Integer
For fila = 1 To nf - 1
For col = 1 To nc - 1
B(fila, col) = A(fila, col)
Next
Next
End Sub
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 496 -
Sub JuegoVida(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer,
semilla As Integer)
Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos As Integer
For fila = 1 To nf - 2
For col = 1 To nc - 2
vecinos = 0
If A(fila, col) < 5 Then
If A(fila, col + 1) = semilla Then vecinos = vecinos + 1
If A(fila + 1, col) = semilla Then vecinos = vecinos + 1
If A(fila, col - 1) = semilla Then vecinos = vecinos + 1
If A(fila - 1, col) = semilla Then vecinos = vecinos + 1
Select Case vecinos
Case 1, 2, 3, 4 : B(fila, col) = semilla
Case 0
B(fila, col) = A(fila, col)
End Select
Else
B(fila, col) = A(fila, col)
End If
Next
Next
IniciarPantalla(A, nf, nc, 0)
TranferirMatriz(B, A, nf, nc)
End Sub
Function ContarLetra(Cadena As String, letra As Char)
Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant
End Function
Sub RecuperarModelo(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByRef
nf As Integer, ByRef nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab) + 1
Do While Not (cadena = "")
cadena = cadena & vbTab
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 497 -
A(fila, col) = Val(subcadena)
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub

Sub VerMatriz(ByVal A(,) As Integer, cx As Integer, cy As Integer,


ByVal nf As Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
If A(fila, col) <= 15 Then
Console.SetCursorPosition(cx + col, cy + fila)
Select Case A(fila, col)
Case 0 : Console.ForegroundColor = 12
Case 1 : Console.ForegroundColor = 9
Case 2 : Console.ForegroundColor = 10
Case 3 : Console.ForegroundColor = 11
Case 8 : Console.ForegroundColor = 8
End Select
Console.Write("{0}", A(fila, col))
End If
Next
Next
End Sub
Sub IniciarPantalla(A(,) As Integer, nf As Integer, nc As Integer, valor As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
A(fila, col) = valor
Next
Next
End Sub
Sub MostrarMatriz(A(,) As Integer, nf As Integer, nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Console.Write("{0}{1}", A(fila, col), " ")
Next
Console.WriteLine()
Next
End Sub
End Module

Uso de autómatas celulares detección de bordes


Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 498 -
P606 .Usando un autómata celular Detectar bordes

SE se tiene el siguiente archivo


0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 3 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 3 3 0 0 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 4 0 0 0 0 0 3 3 3 0 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 3 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 3 3 0 0
0 0 0 0 0 1 1 1 1 5 5 5 5 5 1 1 1 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 3 3 3 3 3 0 0
0 0 0 0 0 1 1 1 1 5 5 5 5 5 1 1 1 1 0 0 0 0 0 0 0 2 2 2 0 0 0 0 0 3 3 3 3 0 0 0
0 0 0 0 0 1 1 1 1 5 5 5 5 5 1 1 1 1 0 0 0 0 0 0 2 2 2 2 2 0 0 0 0 3 3 3 0 0 0 0
0 0 0 0 0 1 1 1 1 5 5 5 5 5 1 1 1 1 0 0 0 0 0 2 2 2 0 2 2 2 0 0 0 3 3 0 0 0 0 0
0 0 0 0 0 1 1 1 1 5 5 5 5 5 1 1 1 1 0 0 0 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 0 0
0 0 0 0 0 1 1 1 1 5 5 5 5 5 1 1 1 1 0 0 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 0 0
0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 2 2 2 2 2 2 2 0 0 2 2 2 2 2 2 2 0 0 0
0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 2 2 2 2 0 0 2 0 0 2 2 2 0 2 2 2 0 0 0
0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 2 2 2 2 0 0 2 0 0 2 2 2 2 2 2 2 0 0 0
0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 2 2 2 2 0 0 2 2 2 2 2 2 2 2 2 2 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 2 2 2 2 2 2 2 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Se obtiene los siguiente bordes


Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 499 -

El programa principal es
Module Module1
Sub MAIN()
Dim i As Integer = 1
RecuperarModelo(NombreArchivo, Modelo, nfilas, ncol)
VerMatriz(Modelo, 10, 2, nfilas, ncol)
For i = 1 To 5
JuegoVida(Modelo, nfilas, ncol, i)
Next
JuegoVida(Modelo, nfilas, ncol, 2)
VerMatriz(Modelo, 10, 2, nfilas, ncol)
Console.ReadLine()
End Sub
End Module

Modifque el automata celular a

Sub JuegoVida(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer,


semilla As Integer)
Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos, x1, y1, x2, y2, fila1, col1 As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
vecinos = 0
If fila > 1 Then
y1 = fila - 1
Else
y1 = fila
End If
If fila < nf - 1 Then
y2 = fila + 1
Else
y2 = fila
End If
If col > 1 Then
x1 = col - 1
Else
x1 = col
End If
If col < nc Then
x2 = col + 1
Else
x2 = col
End If
For fila1 = y1 To y2
For col1 = x1 To x2
If (fila1 = fila And col1 = col) Then Continue For
If A(fila1, col1) = semilla Then vecinos = vecinos + 1
Next
Next
If (vecinos = 8) Then
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 500 -
B(fila, col) = 0
Else
B(fila, col) = A(fila, col)
End If
Next
Next
IniciarPantalla(A, nf, nc, 0)
TranferirMatriz(B, A, nf, nc)
End Sub

Automatas celulares para desplzamiento de figuras.


Modifique el juego de a vida a para desplazar en la 4 direccions

Sub JuegoVida(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, semilla


As Integer)
Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos As Integer
For fila = 1 To nf - 2
For col = 1 To nc - 2
vecinos = 0
If A(fila, col) < 5 Then
'If A(fila, col + 1) = semilla Then vecinos = vecinos + 1
'If A(fila + 1, col) = semilla Then vecinos = vecinos + 1
If A(fila, col - 1) = semilla Then vecinos = vecinos + 1
'If A(fila - 1, col) = semilla Then vecinos = vecinos + 1
Select Case vecinos
Case 1 : B(fila, col) = semilla
End Select
Else
B(fila, col) = A(fila, col)
End If
Next
Next
IniciarPantalla(A, nf, nc, 0)
TranferirMatriz(B, A, nf, nc)
End Sub

Lo siguiente aplicación lo vuelve positivo y negativo

Sub JuegoVida(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, semilla


As Integer)
Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos As Integer
For fila = 1 To nf - 2
For col = 1 To nc - 2
Select Case A(fila, col)
Case semilla : B(fila, col) = 0
Case 0 : B(fila, col) = semilla
End Select
Next
Next
IniciarPantalla(A, nf, nc, 0)
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 501 -
TranferirMatriz(B, A, nf, nc)
End Sub

Pruebe el juego de la vida negativa las reglas son negativas


Select Case vecinos
Case 0, 1, 4, 5, 6, 7 : B(fila, col) = 1
Case 2
B(fila, col) = A(fila, col)
Case 3 : B(fila, col) = 1
End Select

Aplique la regla para juego de vida en 3d

Sub MAIN()
Dim I As Integer
RecuperarModelo(NombreArchivo, Modelo, nfilas, ncol)
VerMatriz(Modelo, 10, 2, nfilas, ncol)
semilla = li
VerMatriz(Modelo, 10, 2, nfilas, ncol)
Console.ReadLine()
For I = 0 To 1000
If semilla < ls Then
semilla = semilla + 1
Else
semilla = li
End If
JuegoVida(Modelo, nfilas, ncol, semilla)
VerMatriz(Modelo, 10, 2, nfilas, ncol)
Console.SetCursorPosition(60, 2)
Console.Write(I)
'Console.ReadLine()
Next
Console.ReadLine()
End Sub
End Module

Imports System.IO
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 502 -
Module ModulE2
Public Const maxfilas As Integer = 100
Public Const maxcol As Integer = 100
Public Modelo(maxfilas, maxcol) As Integer
Public cx As Integer = 10
Public cy As Integer = 2
Public semilla As Integer = 5
Public li As Integer = 1
Public ls As Integer = 9
Public nfilas As Integer = 4
Public ncol As Integer = 4
Public ng As Integer = 100
'Public NombreArchivo As String = "c:\datos1\gosper40x20.txt"
Public NombreArchivo As String = "c:\datos1\gosper40x201.txt"
Sub TranferirMatriz(ByVal A(,) As Integer, ByVal B(,) As Integer, ByVal nf As Integer,
ByVal nc As Integer)
Dim fila, col As Integer
For fila = 1 To nf - 1
For col = 1 To nc - 1
B(fila, col) = A(fila, col)
Next
Next
End Sub
Sub JuegoVida(ByVal A(,) As Integer,
ByVal nf As Integer, ByVal nc As Integer, semilla As Integer)
Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos, x1, y1, x2, y2, fila1, col1 As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
vecinos = 0
If fila > 1 Then
y1 = fila - 1
Else
y1 = fila
End If
If fila < nf - 1 Then
y2 = fila + 1
Else
y2 = fila
End If
If col > 1 Then
x1 = col - 1
Else
x1 = col
End If
If col < nc Then
x2 = col + 1
Else
x2 = col
End If
For fila1 = y1 To y2
For col1 = x1 To x2
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 503 -
If (fila1 = fila And col1 = col) Then Continue For
If A(fila1, col1) = semilla Then vecinos = vecinos + 1
Next
Next
If A(fila, col) = semilla Then
B(fila, col) = semilla + vecinos / 4
If B(fila, col) > ls Then
Dim r As Integer
r = Int(Rnd() * (ls - li))
B(fila, col) = r
End If
Else
If vecinos = 3 Or vecinos = 4 Then
B(fila, col) = semilla
Else
B(fila, col) = A(fila, col)
End If
End If
Next
Next
IniciarPantalla(A, nf, nc, 0)
TranferirMatriz(B, A, nf, nc)
'semilla = semilla + 1
End Sub
Function ContarLetra(Cadena As String, letra As Char)
Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant
End Function
Sub RecuperarModelo(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByRef
nf As Integer, ByRef nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab) + 1
Do While Not (cadena = "")
cadena = cadena & vbTab
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = Val(subcadena)
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 504 -
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub

Sub VerMatriz(ByVal A(,) As Integer, cx As Integer, cy As Integer,


ByVal nf As Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
If A(fila, col) <= 15 Then
Console.SetCursorPosition(cx + col, cy + fila)
'Select Case A(fila, col)
' Case 0 : Console.ForegroundColor = 12
' Case 1 : Console.ForegroundColor = 10
'End Select
Console.ForegroundColor = A(fila, col) + 5
Console.Write("{0}", A(fila, col))
End If
Next
Next
End Sub
Sub IniciarPantalla(A(,) As Integer, nf As Integer, nc As Integer, valor As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
A(fila, col) = valor
Next
Next
End Sub

Sub MostrarMatriz(A(,) As Integer, nf As Integer, nc As Integer)


Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Console.Write("{0} {1}", A(fila, col), vbTab)
Next
Console.WriteLine()
Next
End Sub
End Module

UTLIMA REGLA pruebe y vea los resultados


Sub JuegoVida(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, semilla
As Integer)
Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos1, vecinos2, r As Integer
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 505 -
For fila = 1 To nf - 2
For col = 1 To nc - 2
vecinos1 = 0
vecinos2 = 0
If A(fila, col + 1) = semilla Then vecinos1 = vecinos1 + 1
If A(fila + 1, col) = semilla Then vecinos1 = vecinos1 + 1
If A(fila, col - 1) = semilla Then vecinos1 = vecinos1 + 1
If A(fila - 1, col) = semilla Then vecinos1 = vecinos1 + 1
If A(fila, col + 1) = 0 Then vecinos2 = vecinos2 + 1
If A(fila + 1, col) = 0 Then vecinos2 = vecinos2 + 1
If A(fila, col - 1) = 0 Then vecinos2 = vecinos2 + 1
If A(fila - 1, col) = 0 Then vecinos2 = vecinos2 + 1
'Dim r = Int(Rnd() * 8)
r=2
If vecinos1 > r Then
B(fila, col) = 0
Else
If vecinos2 >= r Then
B(fila, col) = semilla
Else
B(fila, col) = A(fila, col)
End If
End If
Next
Next
IniciarPantalla(A, nf, nc, 0)
TranferirMatriz(B, A, nf, nc)
End Sub

6.9 COMPUTACION UNIVERSAL

Mediante la construcción de un AC sencillo, llamado “ Wireworld” es posible construir


todos los componentes lógicos de una computadora universal [Dewnwey 1990]. “
Wireworld “ es un AC de 4 estados con 9 vecinos (vecindario de Moore), donde cada
estado significa lo siguiente : (0) celda de fondo, (1) celda de cable , (2) cabeza de
electrón y (3) cola de electrón. Las reglas de evolución son las siguientes:
1) Una celda cable(1) cambia a una cabeza de electrón (2) si una o dos celdas
vecinas con cabezas de electrón, de lo contrario se mantiene igual.
2) Una celda cabeza de electrón (2) siempre cambia a cola de electrón (3).
3) Una cola de electrón (3) siempre cambia a cable (1).
4) Las celdas de fondo(0) nunca cambian.

MEJORADO

Problema del cable


0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 3 2 1 1 1 1 1 1 0
0 1 0 0 0 0 0 1 0 0 1 0
0 1 0 0 0 0 0 1 0 0 1 0
0 1 0 0 0 0 0 1 1 1 1 0
0 1 0 0 1 0 0 1 0 0 1 0
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 506 -
0 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0

Imports System.IO
Module Module1
Sub main()
Dim fila As Integer
Console.WriteLine(" PROGRAMACION UNIVERSAL ")
Console.WriteLine("CARGA el archivo diseñado en excel ")
RecuperarMatriz(nombrearchivo, A, nf, nc)
VerPantalla(A, nf, nc, 1, 1)
console.writeline("presione tecla para continuar")
console.readline()
For fila = 0 To ng - 1
Console.Clear()
JuegoVida2(A, nf, nc)
VerPantalla(A, nf, nc, 1, 1)
Console.ForegroundColor = CType(14, ConsoleColor)
Console.SetCursorPosition(60, 1)
Console.Write("generacion {0}", fila)
fila = fila + 1
System.Threading.Thread.Sleep(50)
' Console.ReadLine()
Next
Console.ReadLine()
End Sub
End Module

Imports System.IO
Module Module2
Public Const maxcol As Integer = 80
Public Const maxfilas As Integer = 24
Public A(maxfilas, maxcol) As Integer
Public nf As Integer = 10
Public nc As Integer = 10
Public ng As Integer = 100
Public NombreArchivo As String = "E:\datos\cable4.txt"
Sub IniciarMatriz(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 507 -
For col = 0 To nc - 1
' A(fila, col) = CInt(1 + Rnd() * 7)
A(fila, col) = 0
Next
Next
End Sub
Sub VerPantalla(ByVal Matriz(,) As Integer, ByVal nf As Integer, ByVal nc As Integer,
ByVal cx As Integer, ByVal cy As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Select Case Matriz(fila, col)
Case 0 : Console.ForegroundColor = CType(0, ConsoleColor)
Case 1 : Console.ForegroundColor = CType(12, ConsoleColor)
Case 2 : Console.ForegroundColor = CType(10, ConsoleColor)
Case 3 : Console.ForegroundColor = CType(9, ConsoleColor)
Case 8 : Console.ForegroundColor = CType(14, ConsoleColor)
End Select
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
Next
Next
End Sub

Sub TransferirMatriz(ByVal Matriz(,) As Integer, ByRef m1(,) As Integer, ByVal nf As


Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf
For col = 0 To nc
m1(fila, col) = Matriz(fila, col)
Next
Next
End Sub

Sub JuegoVida2(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer)


Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos As Integer
IniciarMatriz(B, nf, nc)
For fila = 0 To nf
For col = 0 To nc
Select Case A(fila, col)
Case 0 : B(fila, col) = 0
Case 1 : vecinos = 0
If (A(fila, col + 1) = 2) Then vecinos += 1
If (A(fila + 1, col + 1) = 2) Then vecinos += 1
If (A(fila + 1, col) = 2) Then vecinos += 1
If (A(fila + 1, col - 1) = 2) Then vecinos += 1
If (A(fila, col - 1) = 2) Then vecinos += 1
If (A(fila - 1, col - 1) = 2) Then vecinos += 1
If (A(fila - 1, col) = 2) Then vecinos += 1
If (A(fila - 1, col + 1) = 2) Then vecinos += 1
REM B(fila)(col)=A(fila)(col) rem
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 508 -
If (vecinos >= 1 And vecinos <= 2) Then
B(fila, col) = 2
Else : B(fila, col) = 1
End If
Case 2 : B(fila, col) = 3
Case 3 : B(fila, col) = 1
End Select
Next
Next
REM traspone la matriz B a la A
IniciarMatriz(A, nf, nc)
TransferirMatriz(B, A, nf, nc)
End Sub
Function ContarLetra(Cadena As String, letra As Char)
Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant
End Function

Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByRef


nf As Integer, ByRef nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab) + 1
Do While Not (cadena = "")
cadena = cadena & vbTab
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = Val(subcadena)
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
End Module
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 509 -

Objeto cable con tres electrones mismo sentido

Objeto cable con 4 electrones de diferentes sentidos

Se ve que se duplica y se anula


Barreras . Este es un circuito que impide que una señal pase , cualquier que sea su
dirección

Diodos. Los diodos fuerzan a una señal a viajar en un solo sentido-

Cable grueso se genera muchas señales

Compuerta OR. La compuerta Or tomas dos entradas y aplica la operación OR de


señales. En la figura se observa un puerto OR con dos relojes, uno de periodo 2 y otro
de period 4, alternando la seña true Or true / false Or true
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 510 -

Compuerta AND

Complemento (NOT): invierte una señal , es decir , si hay señal en el resultado no la


hay, si por el contrario no hay señal en el resultado si la hay

Puerta not si no hay señal la genera


Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 511 -

APLICACIONES DE AUTÓMATAS
CIENCIAS SOCIALES: CRECIMIENTO POBLACIONAL
BIOLOGÍA: EXPANSIÓN DE ENFERMEDADES
SEGURIDAD: EVACUACIÓN DE EDIFICIOS YBARCOS EN EMERGENCIA
MINERÍA: POZOS PETROLEROS
AVIACIÓN: MODELOS DE COMBATE Y RADARES
TRANSPORTE: SIMULACIÓN DE TRÁFICOVEICULAR

Tarea: Diseñar un modelo en excel de 200 x 200 y mostrar en una pantallla de 24x80

6.10 EJERCICIOS RESUELTOS

PC608 . Encontrar el primer elemento del vector B que no este en A y que elemento es

Imports System.IO
Module Module1
Sub MostrarVector(ByVal A() As Integer, ByVal ne As Integer)
Dim i As Integer
For i = 0 To ne - 1
Console.Write("{0,4} ", A(i))
Next
End Sub

Function encontrar(ByVal A() As Integer, ByVal B() As Integer, ByVal ne As Integer)


As Integer
Dim i, j, elementoB As Integer
Dim encontrado1 As Boolean = False, encontrado2 As Boolean
For i = 0 To ne - 1
encontrado2 = False
For j = 0 To ne - 1
If (B(i) = A(j)) Then
encontrado2 = True
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 512 -
Exit For
End If
Next
If (encontrado2 = False) Then
elementoB = B(i)
encontrado1 = True
Exit For
End If
Next
If (encontrado1 = True) Then
Return elementoB
Else : Return -1
End If
End Function

Sub main()
Dim A() As Integer = {0, 1, 2}
Dim B() As Integer = {0, 1, 3}
ReDim Preserve A(3)
ReDim Preserve B(3)
Dim ne As Integer = 3, elemento As Integer
elemento = encontrar(A, B, 4)
Console.WriteLine()
Console.WriteLine(" Vector A")
MostrarVector(A, ne)
Console.WriteLine()
Console.WriteLine(" Vector B")
MostrarVector(B, ne)
Console.WriteLine()
If (elemento >= 0) Then
Console.WriteLine(" elemento que esta en B pero no en A {0}", elemento)
Else : Console.WriteLine(" estan todos los elementos")
End If
Console.ReadLine()
End Sub
End Module

C609 Se ingresan las 4 coordendas de un cuadrilatero encontrar el diagonal

Imports System.IO
Module Module1

Const npuntos As Integer = 5


Sub MostrarVector(ByVal A() As Integer, ByVal ne As Integer)
Dim i As Integer
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 513 -
For i = 0 To ne - 1
Console.Write("{0,4} ", A(i))
Next
End Sub

Sub diagonal(ByVal X() As Integer, ByVal Y() As Integer, ByVal ne As Integer, _


ByVal tri() As Integer, ByRef ini1 As Integer, ByRef fin1 As Integer)
Dim a, b, c As Integer
Dim ini As Integer = 0, fin As Integer = 0
Dim d1, d2, d3, x1, x2, x3, y1, y2, y3, mayor As Single
a = tri(0)
b = tri(1)
c = tri(2)
x1 = X(a)
y1 = Y(a)
x2 = X(b)
y2 = Y(b)
x3 = X(c)
y3 = Y(c)
REM distancia entre y b
d1 = CSng(Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2)))
d2 = CSng(Math.Sqrt(Math.Pow(x2 - x3, 2) + Math.Pow(y2 - y3, 2)))
d3 = CSng(Math.Sqrt(Math.Pow(x3 - x1, 2) + Math.Pow(y3 - y1, 2)))
mayor = d1
ini = a
fin = b
If (d2 > mayor) Then
mayor = d2
ini = b
fin = c
End If
If (d3 > mayor) Then
mayor = d3
ini = c
fin = a
End If
ini1 = ini
fin1 = fin
End Sub

sub main()
Dim X() As Integer = {0, 2, 2, 0}
Dim Y() As Integer = {0, 0, 2, 2}
Dim ini As Integer = 1, fin As Integer = 2, ne As Integer = 4
Dim A() As Integer = {0, 1, 2}
ReDim Preserve X(npuntos)
ReDim Preserve Y(npuntos)
ReDim Preserve A(3)
Console.Write(" Vector X")
MostrarVector(X, ne)
Console.WriteLine()
Console.Write(" Vector Y")
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 514 -
MostrarVector(Y, ne)
diagonal(X, Y, 3, A, ini, fin)
Console.WriteLine()
Console.WriteLine(" diagonal es del Vertice {0} al vertice {1} ", ini, fin)
Console.ReadLine()
End Sub
End Module

C610 se ingresan centro x , centro y e radio de n circulos encontrar cuantos


de esos circulos son iguales y listar los circulos que se repiten como se
muestra

Imports System.IO

Module Module1
Const npuntos As Integer = 5
Sub MostrarVector(ByVal A(,) As Single, ByVal ne As Integer)
Dim i As Integer
For i = 0 To ne - 1
Console.WriteLine("{0,4} {1,4} {2,4} ", A(i, 0), A(i, 1), A(i, 2))
Next
End Sub
Function BorrarRep(ByVal A(,) As Single, ByRef B(,) As Single, ByVal np As Integer)
As Integer
Dim cx, cy, radio As Single
Dim encontrado As Boolean = False
Dim cont, i, j As Integer
cont = 0
For i = 0 To np - 1
cx = A(i, 0)
cy = A(i, 1)
radio = A(i, 2)
encontrado = False
For j = 0 To cont - 1
If (cx = B(j, 1) And cy = B(j, 1) And radio = B(j, 2)) Then encontrado = True
Next
If (encontrado = False) Then
B(cont, 0) = cx
B(cont, 1) = cy
B(cont, 2) = radio
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 515 -
cont += 1
End If
Next
Return cont
End Function

Sub main()
Dim A(5, 3) As Single
A(0, 0) = 0 : A(0, 1) = 1 : A(0, 2) = 1
A(1, 0) = 0 : A(1, 1) = 1 : A(1, 2) = 1
A(2, 0) = 0 : A(2, 1) = 1 : A(2, 2) = 1
A(3, 0) = 1 : A(3, 1) = 1 : A(3, 2) = 1
A(4, 0) = 0 : A(4, 1) = 1 : A(4, 2) = 1
Dim np As Integer = 5, cont As Integer
Dim B(5, 3) As Single
cont = BorrarRep(A, B, np)
MostrarVector(A, np)
Console.WriteLine()
Console.WriteLine(" cantidad de elementos que se repiten {0}", cont)
MostrarVector(B, cont)
Console.ReadLine()
End Sub
End Module

Localización de multiples instalaciones TRERLO

6.11 PROBLEMAS PROPUESTOS

1. Elaborar un programa para calcular la matriz inversa


2. Calcular la determinante de una matriz
3. Elaborar programas en C++ para lo demás tipos de regresiones como parabólica,
exponencial, logarítmica, polinomial, potencial, Etc.

4. Juego de ajedrez
En el juego de ajedrez las piezas blancas se codifican de la siguiente manera.
1 = peón 2 = Alfil 3 = Caballo
4 = torre 5 = Reyna 6 = Rey 0 = Casillero vacío
Las fichas negras se codifican de igual manera pero con signo negativo.
a) Mostrar la disposición inicial de la pieza en el tablero.
b) Se ingresa el código de la pieza y la fila y columna donde se encuentra ubicado.
Mostrar en la pantalla todos los posibles movimientos de la pieza.
c) Permitir jugar a dos jugadores en la pantalla del computador por turnos. Para ello se
debe validar las jugadas correctas.
d) Explicar los posibles movimientos de una pieza en el tablero
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 516 -

6.12 OTROS

Girar una figura

Imports System.IO
Module Module1
Const lado As Integer = 3
Sub main()
Dim ne As Integer = 3, cx As Integer = 10, cy As Integer = 5, vel As Integer = 120
Dim A1(,) As Integer = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
Dim A2(,) As Integer = {{0, 1, 0}, {0, 1, 0}, {0, 1, 0}}
Dim A3(,) As Integer = {{0, 0, 1}, {0, 1, 0}, {1, 0, 0}}
Dim A4(,) As Integer = {{0, 0, 0}, {1, 1, 1}, {0, 0, 0}}
While CBool((1))
MostrarColor(A1, cx, cy, ne, 14)
System.Threading.Thread.Sleep(vel)
MostrarColor(A1, cx, cy, ne, 0)
MostrarColor(A2, cx, cy, ne, 14)
System.Threading.Thread.Sleep(vel)
MostrarColor(A2, cx, cy, ne, 0)
MostrarColor(A3, cx, cy, ne, 14)
System.Threading.Thread.Sleep(vel)
MostrarColor(A3, cx, cy, ne, 0)
MostrarColor(A4, cx, cy, ne, 14)
System.Threading.Thread.Sleep(vel)
MostrarColor(A4, cx, cy, ne, 0)
End While
Console.ReadLine()
End Sub
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 517 -
Sub MostrarColor(ByVal A(,) As Integer, ByVal cx As Integer, ByVal cy As Integer,
ByVal lado As Integer, ByVal color As Integer)
Dim fila, col As Integer
For fila = 0 To lado - 1
For col = 0 To lado - 1
If (A(fila, col) > 0) Then
Console.ForegroundColor = CType(color, ConsoleColor)
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
End If
Next
Next
End Sub
End Module

DIAGRAMA DE VORONOI CON CRECIMIENTO CIRCULAR Usado en geometria


social

Imports System.IO
Module Module1
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Const NFilas As Integer = 24, NCol As Integer = 80
Dim np As Integer = 10
Dim Matriz(NFilas, 3) As Integer

Sub IniciarMatriz(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer)


Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
A(fila, col) = 0
Next
Next
End Sub

Sub VerPantalla(ByVal cx As Integer, ByVal cy As Integer, ByVal A(,) As Integer,


ByVal nf As Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 518 -
For col = 0 To nc - 1
'Console.BackgroundColor = CType(A(fila, col), ConsoleColor)
Console.ForegroundColor = CType(A(fila, col), ConsoleColor)
Console.SetCursorPosition(col, fila)
Console.Write("*")
Next
Next
End Sub

Sub Main()
Dim A(NFilas, NCol) As Integer
Dim nf As Integer = NFilas, nc As Integer = NCol
Dim X(16) As Integer, Y(16) As Integer
Dim relleno(16) As Integer, k As Integer
Dim np As Integer = 10
Dim r As Single
RecuperarMatriz("e:\DATOS\MATRIZ3X10.TXT", A, np, 3)
MatrizXYZ(A, np, X, Y, relleno)
IniciarMatriz(A, nf, nc)
For r = 1 To 20
crecerCirculo(A, X, Y, nf, nc, relleno, r, np)
VerPantalla(1, 1, A, nf, nc)
System.Threading.Thread.Sleep(10) ' 1 segundo
Next
Console.ForegroundColor = CType(15, ConsoleColor)
For k = 0 To np - 1
Console.CursorLeft = X(k)
Console.CursorTop = Y(k)
Console.Write("{0}", k + 1)
Next
Console.ReadLine()
End Sub

Sub crecerCirculo(ByVal A(,) As Integer, ByVal X() As Integer, ByVal Y() As Integer,
ByVal nf As Integer, _
ByVal nc As Integer, ByVal relleno() As Integer, ByVal r As Single, ByVal np As
Integer)
Dim x1 As Integer, y1 As Integer, k As Integer
For k = 0 To np - 1
For y1 = CInt(Y(k) - r) To CInt(Y(k) + r)
For x1 = CInt(X(k) - r) To CInt(X(k) + r)
If (Math.Pow(x1 - X(k), 2) + Math.Pow(y1 - Y(k), 2) <= r * r) And (x1 > 0)
And (x1 < 80) And (y1 > 0) And (y1 < 25) Then
If (A(y1, x1) = 0) Then
A(y1, x1) = relleno(k)
End If
End If
Next
Next
Next
End Sub
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 519 -
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByVal A(,) As Integer, ByVal nf
As Integer, ByVal nc As Integer)
Dim srlector As StreamReader
srlector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
For fila = 0 To nf - 1
cadena = srlector.ReadLine()
cadena = cadena & Chr(9)
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = CInt(CSng(Val(subcadena)))
inicio = pos + 1
Next
Next
srlector.Close()
End Sub

Sub MatrizXYZ(ByVal A(,) As Integer, ByVal nf As Integer, ByRef X() As Integer,


ByRef Y() As Integer, ByRef Z() As Integer)
For fila = 0 To nf - 1
X(fila) = A(fila, 0)
Y(fila) = A(fila, 1)
Z(fila) = A(fila, 2)
Next
End Sub
End Module
Convertir una matriz de numero en arreglos
Juego de la vida
Suma= A[fila][col-1]+ A[fila-1][col]+ A[fila][col] + A[fila+1][col]+ A[fila][col+1];
B[fila][col]= suma %2;

INVESTIGACION

Elaborar aplicaciones de autómatas celulares


Se ingresan tres puntos calculara la ecuacion de la circunferencia que pasa por esos
tres puntos

CABLE mejorado

Se tiene el siguiente archivo de texto llamado cable


0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 3 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 520 -
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Imports System.IO
Module Module1
Const maxfilas As Integer = 25, maxcol As Integer = 81
Sub main()
Dim A(maxfilas, maxcol) As Integer, nf As Integer = 24, nc As Integer = 78, i As
Integer, ng As Integer = 100
RecuperarMatriz("E:\datos\cable.txt", A, nf, nc)
VerPantalla(A, nf, nc, 1, 1)
Console.ForegroundColor = ConsoleColor.Yellow
console.writeline("presione tecla para continuar")
console.readline()

i=0
While CBool((1))
JuegoVida2(A, nf, nc)
VerPantalla(A, nf, nc, 1, 1)
Console.SetCursorPosition(60, 1)
Console.Write("generacion {0}", i)
i=i+1
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 521 -
System.Threading.Thread.Sleep(50)
End While
Console.SetCursorPosition(60, 1)
Console.Write("generacion {0}", i)
Console.ReadLine()
End Sub

Sub IniciarMatriz(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer)


Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
A(fila, col) = CInt(1 + Rnd() * 7)
Next
Next
End Sub

Sub VerPantalla(ByVal Matriz(,) As Integer, ByVal nf As Integer, ByVal nc As Integer,


ByVal cx As Integer, ByVal cy As Integer)
Dim fila, col As Integer
For fila = 0 To nf
For col = 0 To nc
Console.SetCursorPosition(cx + col, cy + fila)
Select Case Matriz(fila, col)
Case 0 : Console.ForegroundColor = ConsoleColor.Black
Console.WriteLine(" ")
Case 1 : Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("*")
Case 2 : Console.ForegroundColor = ConsoleColor.Green
Console.WriteLine("*")
Case 3 : Console.ForegroundColor = ConsoleColor.Blue
Console.WriteLine("*")
End Select
Next
Next
End Sub

Sub TransferirMatriz(ByVal Matriz(,) As Integer, ByRef m1(,) As Integer, ByVal nf As


Integer, ByVal nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf
For col = 0 To nc
m1(fila, col) = Matriz(fila, col)
Next
Next
End Sub

Sub JuegoVida2(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer)


Dim B(maxfilas, maxcol) As Integer
Dim fila, col, vecinos As Integer
IniciarMatriz(B, nf, nc)
For fila = 0 To nf
For col = 0 To nc
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 522 -
Select Case A(fila, col)
Case 0 : B(fila, col) = 0
Case 1 : vecinos = 0
If (A(fila, col + 1) = 2) Then vecinos += 1
If (A(fila + 1, col + 1) = 2) Then vecinos += 1
If (A(fila + 1, col) = 2) Then vecinos += 1
If (A(fila + 1, col - 1) = 2) Then vecinos += 1
If (A(fila, col - 1) = 2) Then vecinos += 1
If (A(fila - 1, col - 1) = 2) Then vecinos += 1
If (A(fila - 1, col) = 2) Then vecinos += 1
If (A(fila - 1, col + 1) = 2) Then vecinos += 1
REM B(fila)(col)=A(fila)(col) rem
If (vecinos >= 1 And vecinos <= 2) Then
B(fila, col) = 2
Else : B(fila, col) = 1
End If
Case 2 : B(fila, col) = 3
Case 3 : B(fila, col) = 1
End Select
Next
Next
REM traspone la matriz B a la A
IniciarMatriz(A, nf, nc)
TransferirMatriz(B, A, nf, nc)
End Sub

Function ContarLetra(Cadena As String, letra As Char)


Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant
End Function

Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByRef


nf As Integer, ByRef nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab)
Do While Not (cadena = "")
cadena = cadena & vbTab
inicio = 1
For col = 0 To nc - 1
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 523 -
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = Val(subcadena)
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
End Module

Determinar si se cruzan o no lineas

Module Module1

Public X() As Single = {1, 3, 3, 1}


Public Y() As Single = {1, 1, 5, 4}
Public V1() As Integer = {0, 0, 0, 1, 1, 2, 1, 3}
Public V2() As Integer = {1, 2, 3, 2, 3, 3, 0, 2}
Public np As Integer = 4
Public nvert As Integer = 6
Sub MostrarVector(A() As Integer, np As Integer)
Dim fila As Integer
For fila = 0 To np - 1
Console.Write("{0}{1} ", A(fila), vbTab)
Next
Console.WriteLine()
End Sub
Sub MostrarVectorReal(A() As Single, np As Single)
Dim fila As Integer
For fila = 0 To np - 1
Console.Write("{0}{1} ", A(fila), vbTab)
Next
Console.WriteLine()
End Sub
Sub linea(x1 As Single, y1 As Single, x2 As Single, y2 As Single, ByRef a As Single,
ByRef b As Single, ByRef dx As Single)
b = (y2 - y1) / (x2 - x1)
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 524 -
a = y1 - b * x1
dx = Math.Abs(x2 - x1)
End Sub

Function cruce(X() As Single, Y() As Single, v1() As Integer, V2() As Integer, recta1
As Integer, recta2 As Integer) As Integer
Dim x1, y1, x2, y2, x3, y3, x4, y4, a1, b1, a2, b2, dx1, dx2, inferior, superior As
Single
Dim f1, f2, d1, d2 As Single
Dim res As Integer
x1 = X(v1(recta1))
y1 = Y(v1(recta1))
x2 = X(V2(recta1))
y2 = Y(V2(recta1))
linea(x1, y1, x2, y2, a1, b1, dx1)
x3 = X(v1(recta2))
y3 = Y(v1(recta2))
x4 = X(V2(recta2))
y4 = Y(V2(recta2))
linea(x3, y3, x4, y4, a2, b2, dx2)
If dx1 < dx2 Then
inferior = x1
superior = x2
Else
inferior = x3
superior = x4
End If
f1 = a1 + b1 * inferior
f2 = a2 + b2 * inferior
d1 = f1 - f2
f1 = a1 + b1 * superior
f2 = a2 + b2 * superior
d2 = f1 - f2
res = d1 * d2
If res >= 0 Then
Return -1
Else
Return 1
End If
End Function

Sub Main()
Dim linea1 As Integer = 0
Dim linea2 As Integer = 1
Dim res As Integer = 0
Console.Write("Vector X ")
MostrarVectorReal(X, np)
Console.Write("Vector Y ")
MostrarVectorReal(Y, np)
Console.Write("Vector V1 ")
MostrarVector(V1, nvert)
Console.Write("Vector V2 ")
Program.y métodos numericos 2019A\ 6. Algebra Lineal Numérica / Ismael Véliz V. - 525 -
MostrarVector(V2, nvert)
res = cruce(X, Y, V1, V2, 0, 1)
Console.WriteLine("CRUCE LINEA 0 CON 1 {0} ", res)
If res >= 0 Then
Console.WriteLine("NO HAY CRUCE {0} ", res)
Else
Console.WriteLine(" HAY CRUCE {0} ", res)
End If
Console.WriteLine("CRUCE LINEA 1 CON 4 {0} ", cruce(X, Y, V1, V2, 1, 4))
Console.WriteLine("CRUCE LINEA 4 CON 1 {0} ", cruce(X, Y, V1, V2, 4, 1))
Console.WriteLine("CRUCE LINEA 5 CON 0 {0} ", cruce(X, Y, V1, V2, 5, 0))
Console.WriteLine("CRUCE LINEA 0 CON 5 {0} ", cruce(X, Y, V1, V2, 0, 5))
Console.ReadLine()
End Sub
End Module

You might also like