Una matriz es una estructura de datos que permite almacenar un conjunto de datos del mismo tipo.
Con un único nombre se define la matriz y por medio de DOS sub índices hacemos referencia a cada elemento de la misma (componente)
Hemos graficado una matriz de 3 filas y 5 columnas. Para hacer referencia a cada elemento debemos indicar primero la fila y luego la columna, por ejemplo en la componente 1,4 se almacena el valor 97.
En este ejemplo almacenamos valores enteros. Todos los elementos de la matriz deben ser del mismo tipo (int, float, string etc.)
Las filas y columnas comienzan a numerarse a partir de cero, similar a los vectores.
Declaración de una Matriz en C#
C# admite matrices de una dimensión, matrices multidimensionales (matrices rectangulares) y matrices de matrices (matrices escalonadas). El siguiente ejemplo muestra cómo declarar diferentes tipos de matrices:
int[] numbers;
Matrices multidimensionales:
string[,] names;
Matrices de matrices (escalonadas):
byte[][] scores;
La declaración de matrices (como se muestra arriba) no crea realmente las matrices. En C#, las matrices son objetos (se explica más adelante en este tutorial) cuyas instancias deben crearse. Los siguientes ejemplos muestran cómo crear matrices:
Matrices unidimensionales:
int[] numbers = new int[5];
Matrices multidimensionales:
string[,] names = new string[5,4];
Matrices de matrices (escalonadas):
byte[][] scores = new byte[5][];
for (int x = 0; x < scores.Length; x++)
{
scores[x] = new byte[4];
}
También se pueden utilizar matrices más grandes. Por ejemplo, se puede utilizar una matriz rectangular de tres dimensiones:
int[,,] buttons = new int[4,5,3];
Incluso, se pueden combinar matrices rectangulares y escalonadas. Por ejemplo, el siguiente código declara una matriz unidimensional que contiene matrices tridimensionales de matrices bidimensionales de tipo int:
int[][,,][,] numbers;
Ejercicios Resueltos de Matrices en C#
Ejemplo 1Crear una matriz de 3 filas por 4 columnas con elementos de tipo int, ingresar sus posiciones y luego imprimirlas.
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace Matriz
{
class Matriz
{
private
int[,] mat;
public void Ingresar()
{
mat = new
int[3, 4];
for
(int f = 0; f < 3; f++)
{
for
(int c = 0; c < 4; c++)
{
Console.Write("Ingrese posicion ["+(f+1)+","+(c+1)+"]:
");
string
linea;
linea = Console.ReadLine();
mat[f, c] = int.Parse(linea);
}
}
}
public void Imprimir()
{
for
(int f = 0; f < 3; f++)
{
for
(int c = 0; c < 4; c++)
{
Console.Write(mat[f,
c] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
static void Main(string[]
args)
{
Matriz ma = new Matriz();
ma.Ingresar();
ma.Imprimir();
}
}
}
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
Matriz
{
class Matriz
{
private
int[,] mat;
public void Cargar()
{
mat = new
int[3, 4];
for (int f = 0; f < 3;
f++)
{
for (int
c = 0; c < 4; c++)
{
Console.Write("Ingrese posicion ["+(f+1)+","+(c+1)+"]: ");
string
linea;
linea = Console.ReadLine();
mat[f, c] = int.Parse(linea);
}
}
}
public void
PrimerFila()
{
Console.WriteLine("\nPrimer
fila de la matriz:");
for (int c = 0; c
< 4; c++)
{
Console.Write(mat[0, c]+" ");
}
}
public void
UltimaFila()
{
Console.WriteLine("\nUltima
fila de la matriz:");
for (int c = 0; c
< 4; c++)
{
Console.Write(mat[2, c]+" ");
}
}
public void
PrimerColumna()
{
Console.WriteLine("\nPrimer
columna:");
for (int f = 0; f
< 3; f++)
{
Console.Write(mat[f, 0]+" ");
}
}
static void Main(string[] args)
{
Matriz ma = new Matriz();
ma.Cargar();
ma.PrimerFila();
ma.UltimaFila();
ma.PrimerColumna();
Console.ReadKey();
}
}
}
Realizar un programa que permita imprimir la siguiente serie:
1 0 1 0 1 0
1 0 1 0 1 0
1 0 1 0 1 0
1 0 1 0 1 0
1 0 1 0 1 0
1 0 1 0 1 0
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace PruebaVector
{
class PruebaVector
{
private int[,] serie;
public void Cargar()
{
serie = new
int[10, 10];
for (int i = 1; i <= 6;
i++)
{
for
(int j = 1; j <= 6; j++)
{
if
(j % 2 == 0)
{
serie[i, j] = 0;
}
else
{
serie[i, j] = 1;
}
}
}
}
public void visualizar()
{
for
(int i = 1; i <= 5; i++)
{
Console.Write("\n");
for
(int j = 1; j <= 6; j++)
{
Console.Write(serie[i,
j] + " ");
}
}
Console.ReadKey();
}
static void Main(string[]
args)
{
PruebaVector pv = new
PruebaVector();
pv.Cargar();
pv.visualizar();
}
}
}
Al ejecutar el código muestra el siguiente resultado
Suma de Matrices en C#
Ejemplo 4
Realizar un programa que permita la suma de dos matrices de 3x3 y el resultado almacenar en un tercer matriz
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PruebaVector
{
class PruebaVector
{
private int[,] MatrizA;
private int[,] MatrizB;
private int[,] MatrizC;
public void Cargar()
{
MatrizA = new int[10,10];
MatrizB = new int[10, 10];
MatrizC = new int[10, 10];
Console.WriteLine("Ingresando datos al matriz A");
for (int i = 1; i<= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.Write("Ingrese posicion [" + i + "," + j + "]: ");
string linea;
linea = Console.ReadLine();
MatrizA[i, j] = int.Parse(linea);
}
}
Console.WriteLine("Ingresando datos al matriz B");
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.Write("Ingrese posicion [" + i + "," + j + "]: ");
string linea;
linea = Console.ReadLine();
MatrizB[i, j] = int.Parse(linea);
}
}
//Sumamos la matrizA y la MatrizB
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
MatrizC[i,j]=MatrizA[i,j]+MatrizB[i,j];
}
}
}
// visualizamos la suma de las matrices
public void visualizar()
{
Console.WriteLine("La suma de la MatrizA y MatrizB es :");
for (int i = 1; i <= 3; i++)
{
Console.Write("\n");
for (int j = 1; j <= 3; j++)
{
Console.Write(MatrizC[i,j]+" ");
}
}
Console.ReadKey();
}
static void Main(string[] args)
{
PruebaVector pv = new PruebaVector();
pv.Cargar();
pv.visualizar();
}
}
}
Al ejecutar el código muestra el siguiente resultado




