Matrix multiplication: Difference between revisions

→‎{{header|C sharp|C#}}: added implementation as an extension method, and method to show matrix
(→‎{{header|Raku}}: add an other take)
(→‎{{header|C sharp|C#}}: added implementation as an extension method, and method to show matrix)
Line 1,165:
 
This code should work with any version of the .NET Framework and C# language
 
==={{header|Class}}===
 
<syntaxhighlight lang="csharp">public class Matrix
Line 1,210 ⟶ 1,212:
}
}</syntaxhighlight>
 
==={{header|Extension Method}}===
Implementation of matrix multiplication and matrix display for 2D arrays using an extension method
 
<syntaxhighlight lang="csharp">
public static class LinearAlgebra
{
public static double[,] Product(this double[,] a, double[,] b)
{
int na = a.GetLength(0), ma = a.GetLength(1);
int nb = b.GetLength(0), mb = b.GetLength(1);
 
if (ma != nb)
{
throw new ArgumentException("Incompatible Matrix Sizes.", nameof(b));
}
double[,] c = new double[na, mb];
for (int i = 0; i < na; i++)
{
for (int j = 0; j < mb; j++)
{
double sum = 0;
for (int k = 0; k < ma; k++)
{
sum += a[i, k] * b[k, j];
}
c[i, j] = sum;
}
}
return c;
}
public static string Show(this double[,] a, string formatting = "g4", int columnWidth = 12)
{
int na = a.GetLength(0), ma = a.GetLength(1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < na; i++)
{
sb.Append("|");
for (int j = 0; j < ma; j++)
{
sb.Append(" ");
if (columnWidth > 0)
{
sb.Append(a[i, j].ToString(formatting).PadLeft(columnWidth));
}
else if (columnWidth < 0)
{
sb.Append(a[i, j].ToString(formatting).PadRight(columnWidth));
}
else
{
throw new ArgumentOutOfRangeException(nameof(columnWidth), "Must be non-negative");
}
}
sb.AppendLine(" |");
}
return sb.ToString();
}
}
class Program
{
static void Main(string[] args)
{
double[,] A = new double[,] { { 1, 2, 3 }, { 4, 5, 6 } };
double[,] B = new double[,] { { 8, 7, 6 }, { 5, 4, 3 }, { 2, 1, 0 } };
 
double[,] C = A.Product(B);
Console.WriteLine("A=");
Console.WriteLine(A.Show("f4", 8));
Console.WriteLine("B=");
Console.WriteLine(B.Show("f4", 8));
Console.WriteLine("C=A*B");
Console.WriteLine(C.Show("f4", 8));
 
}
}
</syntaxhighlight>
 
{{out}}
<pre>
A=
| 1.0000 2.0000 3.0000 |
| 4.0000 5.0000 6.0000 |
 
B=
| 8.0000 7.0000 6.0000 |
| 5.0000 4.0000 3.0000 |
| 2.0000 1.0000 0.0000 |
 
C=A*B
| 24.0000 18.0000 12.0000 |
| 69.0000 54.0000 39.0000 |
</pre>
 
=={{header|C++}}==
1

edit