Common Matrix Operations
Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 6 de 66.
Las matrices se usan comúnmente en matemáticas y ciencias de la computación. Exploremos algunas operaciones comunes en arreglos 2D.
Sumar dos matrices:
int[][] AddMatrices(int[][] a, int[][] b)
{
int rows = a.Length;
int[][] result = new int[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = new int[a[i].Length];
for (int j = 0; j < a[i].Length; j++)
{
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}Transponer una matriz (intercambiar filas y columnas):
int[][] Transpose(int[][] matrix)
{
int rows = matrix.Length;
int cols = matrix[0].Length;
int[][] result = new int[cols][];
for (int i = 0; i < cols; i++)
{
result[i] = new int[rows];
for (int j = 0; j < rows; j++)
{
result[i][j] = matrix[j][i];
}
}
return result;
}Calcula la suma de cada fila:
int[] RowSums(int[][] matrix)
{
int rows = matrix.Length;
int[] sums = new int[rows];
for (int i = 0; i < rows; i++)
{
int sum = 0;
for (int j = 0; j < matrix[i].Length; j++)
{
sum += matrix[i][j];
}
sums[i] = sum;
}
return sums;
}Multiplicar dos matrices entre sí:
En la multiplicación de matrices, cada elemento
result[i][j] se calcula como el producto punto de la fila i de la primera matriz y la columna j de la segunda matriz — es decir, la suma de matrix1[i][k] * matrix2[k][j] para cada k. La primera matriz debe tener tantas columnas como filas tiene la segunda matriz.int[][] MultiplyMatrices(int[][] a, int[][] b)
{
int rows = a.Length;
int cols = b[0].Length;
int inner = b.Length;
int[][] result = new int[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = new int[cols];
for (int j = 0; j < cols; j++)
{
int sum = 0;
for (int k = 0; k < inner; k++)
{
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}Desafío
DifícilCrea un método llamado multiplyMatrices que:
- Toma dos matrices (matrices jagged 2D) como parámetros: matrix1 y matrix2
- Las multiplica siguiendo las reglas de la multiplicación de matrices
- Devuelve la matriz resultante
Para que la multiplicación de matrices sea válida:
- El número de columnas en matrix1 debe ser igual al número de filas en matrix2
- El resultado tendrá dimensiones: [matrix1.rows × matrix2.columns]
Cómo funciona la multiplicación de matrices:
Cada elemento en la posición [i][j] en el resultado se calcula tomando la fila i de matrix1 y la columna j de matrix2, multiplicando sus elementos correspondientes juntos y sumando todos esos productos:result[i][j] = matrix1[i][0] * matrix2[0][j] + matrix1[i][1] * matrix2[1][j] + ...
En otras palabras: result[i][j] = sum of (matrix1[i][k] * matrix2[k][j]) para cada k.
Por ejemplo, si matrix1 es:
[1, 2]
[3, 4]Y matrix2 es:
[5, 6]
[7, 8]Entonces result[0][0] = 1*5 + 2*7 = 19, result[0][1] = 1*6 + 2*8 = 22, y así sucesivamente. El resultado debería ser:
[19, 22]
[43, 50]Si las matrices no se pueden multiplicar, devuelve null.
Hoja de referencia
Operaciones comunes de matrices usando arreglos jagged 2D:
Sumar dos matrices:
int[][] AddMatrices(int[][] a, int[][] b)
{
int rows = a.Length;
int[][] result = new int[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = new int[a[i].Length];
for (int j = 0; j < a[i].Length; j++)
{
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}Trasponer una matriz (intercambiar filas y columnas):
int[][] Transpose(int[][] matrix)
{
int rows = matrix.Length;
int cols = matrix[0].Length;
int[][] result = new int[cols][];
for (int i = 0; i < cols; i++)
{
result[i] = new int[rows];
for (int j = 0; j < rows; j++)
{
result[i][j] = matrix[j][i];
}
}
return result;
}Calcular la suma de cada fila:
int[] RowSums(int[][] matrix)
{
int rows = matrix.Length;
int[] sums = new int[rows];
for (int i = 0; i < rows; i++)
{
int sum = 0;
for (int j = 0; j < matrix[i].Length; j++)
{
sum += matrix[i][j];
}
sums[i] = sum;
}
return sums;
}Multiplicar dos matrices:
Cada elemento result[i][j] es la suma de los productos de la fila i de la primera matriz y la columna j de la segunda matriz:
result[i][j] += matrix1[i][k] * matrix2[k][j] para cada k.
La primera matriz debe tener tantas columnas como filas tiene la segunda matriz.
int[][] MultiplyMatrices(int[][] a, int[][] b)
{
int rows = a.Length;
int cols = b[0].Length;
int inner = b.Length;
int[][] result = new int[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = new int[cols];
for (int j = 0; j < cols; j++)
{
for (int k = 0; k < inner; k++)
{
result[i][j] += a[i][k] * b[k][j];
}
}
}
return result;
}Pruébalo tú mismo
public class MultiplyMatrices
{
// Implementa el método MultiplyMatrices
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2)
{
// Escribe tu código aquí
}
}Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
Todas las lecciones de Lógica y Flujo
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety