Common Matrix Operations
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 6번째.
행렬은 수학과 컴퓨터 과학에서 흔히 사용됩니다. 2차원 배열에 대한 몇 가지 일반적인 연산을 살펴보겠습니다.
두 행렬을 더합니다:
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;
}행렬 전치(행과 열을 바꿈):
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;
}각 행의 합계를 계산합니다:
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;
}두 행렬을 서로 곱합니다:
행렬 곱셈에서 각 요소 result[i][j]는 첫 번째 행렬의 i행과 두 번째 행렬의 j열을 가져와 해당 요소들을 곱하고 그 곱들의 합을 구하여 계산됩니다. 공식적으로는 모든 유효한 k 값에 대해 result[i][j] = sum of matrix1[i][k] * matrix2[k][j]입니다.
이 작업이 가능하려면 matrix1의 열 개수가 matrix2의 행 개수와 같아야 합니다. 결과 행렬의 크기는 [matrix1.rows × matrix2.cols]가 됩니다.
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;
}챌린지
어려움다음과 같은 기능을 수행하는 multiplyMatrices 메서드를 작성하세요:
- 두 개의 행렬(2차원 가변 배열)을 매개변수로 받습니다: matrix1 및 matrix2
- 행렬 곱셈 규칙에 따라 두 행렬을 곱합니다
- 결과 행렬을 반환합니다
행렬 곱셈이 유효하려면 다음 조건을 만족해야 합니다:
- matrix1의 열 개수가 matrix2의 행 개수와 같아야 합니다
- 결과 행렬의 크기는 [matrix1.rows × matrix2.columns]가 됩니다
행렬 곱셈의 작동 방식:
결과 행렬의 [i][j] 위치에 있는 각 요소는 matrix1의 i번째 행과 matrix2의 j번째 열을 가져와서, 대응하는 요소들을 서로 곱한 뒤 그 곱들의 합을 구하여 계산됩니다:result[i][j] = matrix1[i][0] * matrix2[0][j] + matrix1[i][1] * matrix2[1][j] + ...
즉, 각 k에 대해 result[i][j] = sum of (matrix1[i][k] * matrix2[k][j])입니다.
예를 들어, matrix1이 다음과 같고:
[1, 2]
[3, 4]matrix2가 다음과 같다면:
[5, 6]
[7, 8]그러면 result[0][0] = 1*5 + 2*7 = 19, result[0][1] = 1*6 + 2*8 = 22와 같이 계산됩니다. 결과는 다음과 같아야 합니다:
[19, 22]
[43, 50]만약 행렬을 곱할 수 없는 경우, null을 반환하세요.
직접 해보기
public class MultiplyMatrices
{
// MultiplyMatrices 메서드를 구현하세요
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2)
{
// 여기에 코드를 작성하세요
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
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