46 - Estructura de datos tipo matriz. |
Algunas situaciones utilizar un solo subíndice para acceder a un elemento de un vector puede ser inconveniente. El lenguaje VBScript nos permite definir estructuras de datos con dos dimensiones. De esta forma debemos acceder a cada elemento por medio de dos subíndices.
Veamos la sintaxis para definir y acceder a una matriz mediante un ejemplo:
<%option explicit%>
<html>
<head>
<title>problema</title>
</head>
<body>
<%
dim matriz1(2,2)
matriz1(0,0)=1
matriz1(0,1)=1
matriz1(0,2)=1
matriz1(1,0)=2
matriz1(1,1)=2
matriz1(1,2)=2
matriz1(2,0)=3
matriz1(2,1)=3
matriz1(2,2)=3
response.write("Creación de una matriz de dos filas ")
response.write("y dos columnas<br>")
dim f,c
for f=0 to 2
for c=0 to 2
response.write(matriz1(f,c) & "-")
next
response.write("<br>")
next
response.write("Utilización de ubound en una matriz<br>")
for f=0 to ubound(matriz1,1)
for c=0 to ubound(matriz1,2)
response.write(matriz1(f,c) & "-")
next
response.write("<br>")
next
dim matriz2
redim matriz2(2,3)
matriz2(0,0)=1
matriz2(0,1)=1
matriz2(0,2)=1
matriz2(0,3)=1
matriz2(1,0)=2
matriz2(1,1)=2
matriz2(1,2)=2
matriz2(1,3)=2
matriz2(2,0)=3
matriz2(2,1)=3
matriz2(2,2)=3
matriz2(2,3)=3
response.write("Matriz creada dinámicamente<br>")
for f=0 to ubound(matriz2,1)
for c=0 to ubound(matriz2,2)
response.write(matriz2(f,c) & "-")
next
response.write("<br>")
next
redim preserve matriz2(2,2)
response.write("Matriz después de redimensionarla<br>")
for f=0 to ubound(matriz2,1)
for c=0 to ubound(matriz2,2)
response.write(matriz2(f,c) & "-")
next
response.write("<br>")
next
%>
</body>
</html>
Para definir una matriz utilizamos la sintaxis:
dim matriz1(2,2)
El primer subíndice indica las filas (es decir tiene tres filas 0,1 y 2) y el segundo subíndice indica las columnas.
Para inicializar cada componente por asignación:
matriz1(0,0)=1 matriz1(0,1)=1 matriz1(0,2)=1 matriz1(1,0)=2 matriz1(1,1)=2 matriz1(1,2)=2 matriz1(2,0)=3 matriz1(2,1)=3 matriz1(2,2)=3
Primero indicamos la fila y luego la columna.
Podemos imprimir la matriz disponiendo un for dentro de otro:
for f=0 to 2
for c=0 to 2
response.write(matriz1(f,c) & "-")
next
response.write("<br>")
next
La variable f nos indica la fila y la variable c indica la columna de la componente que queremos acceder.
En forma más genérica podemos preguntarle a la matriz mediante la función ubount el valor de la dimensión:
for f=0 to ubound(matriz2,1)
for c=0 to ubound(matriz2,2)
response.write(matriz2(f,c) & "-")
next
response.write("<br>")
next
ubound(matriz2,1) retorna la cantidad de fila de la matriz y ubound(matriz2,2) retorna la cantidad de columnas.
Podemos crear una matriz en forma dinámica:
dim matriz2 redim matriz2(2,3)y por lo tanto en algún momento podemos redimensionarla:
redim preserve matriz2(2,2)