patterncsharpMinor
Returning multiplied matrix array
Viewed 0 times
arraymultipliedreturningmatrix
Problem
Is there a more clever way of writing this piece of code? It does work but I thought there might be a better way of returning a matrix from multiplying the parameter by itself.
public static void Main(string[] args)
{
int[,] m1 = CreateMatrix(5);
}
static int[,] CreateMatrix(int rowscols)
{
int[,] result = new int[rowscols, rowscols];
int res = rowscols * rowscols;
int counter= 0;
for (int i = 0; i < rowscols; ++i)
{
for (int k = 0; k < rowscols; ++k)
{
result[i, k] = (res - counter);
counter += 1;
}
}
return result;
}Solution
rowscols is not a very good name.Although on one hand it's "accurate",
on another it's kind of awkward.
How about
dimension or dim instead?res is also not a very good name.Since its value is
dim * dim,it's the number of cells in the matrix, so
cellCount would be better.It would be better to move the
counter variable inside the loop,by declaring it in the outer loop together with
i,and incrementing it in the innermost loop together with
k.It's a common practice to name loop variables
i, j, k.You skipped
j and went directly for k.It's not a "problem",
but
j would be more natural,especially because at school (I think) they teach matrices typically with \$m_{ij}\$ notation rather than \$m_{ik}\$
Lastly,
since the result of the function is a matrix,
it will be more meaningful to call the variable
matrix instead of result.Suggested implementation
Putting the above suggestions together:
static int[,] CreateMatrix(int dimension)
{
var matrix = new int[dimension, dimension];
var cellCount = dimension * dimension;
for (int i = 0, counter = 0; i < dimension; ++i)
{
for (int j = 0; j < dimension; ++j, ++counter)
{
matrix[i, j] = cellCount - counter;
}
}
return matrix;
}Special thanks to @Abbas for pointing out to use the
var keyword instead of explicitly declaring the matrix and cellCount variables.Code Snippets
static int[,] CreateMatrix(int dimension)
{
var matrix = new int[dimension, dimension];
var cellCount = dimension * dimension;
for (int i = 0, counter = 0; i < dimension; ++i)
{
for (int j = 0; j < dimension; ++j, ++counter)
{
matrix[i, j] = cellCount - counter;
}
}
return matrix;
}Context
StackExchange Code Review Q#68107, answer score: 5
Revisions (0)
No revisions yet.