How to print 2D array to console in C# - c#

I dont't have any code for this, but I do want to know how I could do this. I use visual studio 2010 C# if that matters.
Thanks
Jason

public static void Print2DArray<T>(T[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i,j] + "\t");
}
Console.WriteLine();
}
}

you can print it all on one line
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Console.WriteLine(String.Join(" ", array2D.Cast<int>()));
output
1 2 3 4 5 6 7 8

You should read MSDN:Using foreach with Arrays
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55

//The following are three ways to print any 2d arrays to console:
int[,] twoDArray = new int[3, 4]{ {2,5,55,44},{10,45,5,22 },{ 67,34,56,77} };
Console.WriteLine("Array Code Out Method:1");
int rows = twoDArray.GetLength(0); // 0 is first dimension, 1 is 2nd
//dimension of 2d array
int cols = twoDArray.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write("\t" + twoDArray[i, j]);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
}
Console.WriteLine("Array Code Out Method: 2");
for (int x = 0; x <= twoDArray.GetUpperBound(0); x++)
{
for (int y = 0; y <= twoDArray.GetUpperBound(1); y++)
{
Console.Write("\t"+ twoDArray[x,y]);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
}
Console.WriteLine("Array Code Out Method:3");
foreach (int items in twoDArray)
{
Console.Write(""+ "\t" +items);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
//string example
string[,] friendNames = new string[,] { {"Rosy","Amy"},
{"Peter","Albert"}
};
foreach (string str in friendNames)
{
Console.WriteLine(str);
}

The following is an example...
static void Main()
{
// A. 2D array of strings.
string[,] a = new string[,]
{
{"ant", "aunt"},
{"Sam", "Samantha"},
{"clozapine", "quetiapine"},
{"flomax", "volmax"},
{"toradol", "tramadol"}
};
// B. Get the upper bound to loop.
for (int i = 0; i <= a.GetUpperBound(0); i++)
{
string s1 = a[i, 0]; // ant, Sam, clozapine...
string s2 = a[i, 1]; // aunt, Samantha, quetiapine...
Console.WriteLine("{0}, {1}", s1, s2);
}
Console.WriteLine();
}

int[,] matrix = new int[2, 2] { {2, 2}, {1, 1} };
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int k = 0; k < matrix.GetLength(1); k++ )
{
//put a single value
Console.Write(matrix[i,k]);
}
//next row
Console.WriteLine();
}

private int[,] MirrorH(int[,] matrix)
{
int[,] MirrorHorizintal = new int[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j ++)
{
MirrorHorizintal[i, j] = matrix[i, 3 - j];
}
}
return MirrorHorizintal;
}

Try like this..
int[,] matrix = new int[3, 3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
int rowLength = matrix.GetLength(0);
int colLength = matrix.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", matrix[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.Read();

Below is multiple solution to how to implement multidimentional array, I think it is pretty straight forward in c#.
using System;
using System.Collections.Generic;
namespace DataStructure
{
class Program : SortedZeros
{
static void Main(string[] args)
{
// Two-Dimensional Array
int[,] numbers2D = new int[3, 2]
{
{ 9, 99 },
{ 3, 33 },
{ 5, 55 }
};
// 3 * 3
int[,] dataTest2D = new int[3, 3]
{
{3, 5, 7},
{4, 3, 8},
{9, 6, 9},
};
// A similar array with string elements.
int[,] matrix = new int[4, 4]
{
{1, 2, 3, 6},
{4, 5, 6, 4},
{7, 8, 9, 6},
{7, 8, 9, 2},
};
int rowLength = matrix.GetLength(0);
int colLength = matrix.GetLength(0);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", matrix[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
// using foreach to print out the 2 * 2 in one straightline
foreach (int i in numbers2D)
{
Console.Write("{0} ", i);
}
Console.WriteLine();
Console.WriteLine();
for (int i = 0; i < dataTest2D.GetLength(0); i++)
{
for (int j = 0; j < dataTest2D.GetLength(1); j++)
{
Console.Write(string.Format("{0} ", dataTest2D[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
}
}
}

Explanation:
1. create an array
2. Create 2 for loops (one inside the other)
3. In "j" loop, pass matrix (roomString in our case) as parameter.
4. Add a "+" symbol (concatenate) it with a " " (empty space)
5. In "i" loop, have a "cw tab tab" --> Console.WriteLine();
Code:
string[,] roomString = new string[4, 4]
{
{"0","0","0","0" },
{"0","0","0","0" },
{"0","0","0","0" },
{"0","0","0","0" }
};
for (int i = 0; i < roomString.GetLength(0); i++)
{
for (int j = 0; j < roomString.GetLength(1); j++)
{
Console.Write(roomString[i,j]+" ");
}
Console.WriteLine();
}

Helper function to get any row:
public static int[] GetRow(int[,] mat, int rowNumber)
=> Enumerable.Range(0, mat.GetLength(1))
.Select(i => mat[rowNumber, i])
.ToArray();
Print row values in new line:
int[,] mat = new int[2,2];
for (int i =0; i < mat.GetLength(0); i++)
{
Console.WriteLine(string.Join(",", GetRow(mat, i)));
}

Do it like this:
static public void Print2DArray(int[][] A)
{
foreach (int[] row in A)
{
foreach (int element in row)
{
Console.Write(element.ToString() + " ");
}
Console.WriteLine();
}
}

Related

C# flattening/expanding a 3D matrix into a jagged array

I have to flatted a 3d array in order to be serialized.
Let's start with this:
int[,,] array3D = new int[,,] {
{ { 1, 2 }, { 3, 4 }, {5,6 }, {7,8 } },
{ { 9, 10}, { 11, 12},{ 13,14} , {15,16 }},
{ { 17, 18}, { 19, 20},{ 21,22}, {23,24 } }
};
which makes it like this (something like 1,2,3,4,...,24):
So now I have this s/r
public static T[] Flatten<T>(T[,,] arr)
{
int rows0 = arr.GetLength(0);
int rows1 = arr.GetLength(1);
int rows2 = arr.GetLength(2);
T[] arrFlattened = new T[rows0 * rows1* rows2];
int i, j, k;
for (k = 0; k < rows2; k++)
{
for (j = 0; j < rows1; j++)
{
for (i = 0; i < rows0; i++)
{
var test = arr[i, j, k];
int index = i + j * rows0 + k * rows1;
arrFlattened[index] = test;
}
}
}
return arrFlattened;
}
which flattens the 3d matrix into a 1d array
I am not smart enough to understand if the procedure is correct but let's go further.
I then Expand with the following s/r
public static T[,,] Expand<T>(T[] arr, int rows0, int rows1)
{
int length = arr.GetLength(0);
int rows2 = length / rows0 / rows1;
T[,,] arrExpanded = new T[rows0, rows1, rows2];
for (int k = 0; k < rows2; k++)
{
for (int j = 0; j < rows1; j++)
{
for (int i = 0; i < rows0; i++)
{
T test = arr[i + j * rows0 + k * rows1];
arrExpanded[i, j, k] = test;
}
}
}
return arrExpanded;
}
but the result is the following:
So nothing like 1,2,3,4,5....24
I know that the error might be a trivial one but try as I might I can't find it.
Thank in advance.
Patrick
Thanks for helping all 3 solution were amazing and working but I chose the one more easily to understand and debug for me
I am assuming that you want to know what is the mistake in your code more than you want to know the quickest way to get to the answer. Your index calculation is wrong. You are calculating it like this:
int index = i + j * rows0 + k * rows1;
But you actually need to multiply the last term not just by rows1 but by rows0 too:
int index = i + j * rows0 + k * rows1 * rows0;
Also, it makes sense to swap the order of dimensions that are iterated in for loops to get results in order. The final code for that would be:
public static T[] Flatten<T>(T[,,] arr)
{
int rows0 = arr.GetLength(0);
int rows1 = arr.GetLength(1);
int rows2 = arr.GetLength(2);
T[] arrFlattened = new T[rows0 * rows1* rows2];
int i, j, k;
for (k = 0; k < rows0; k++)
{
for (j = 0; j < rows1; j++)
{
for (i = 0; i < rows2; i++)
{
var test = arr[k, j, i];
int index = i + j * rows2 + k * rows1 * rows2;
arrFlattened[index] = test;
}
}
}
return arrFlattened;
}
public static T[,,] Expand<T>(T[] arr, int rows0, int rows1)
{
int length = arr.GetLength(0);
int rows2 = length / rows0 / rows1;
T[,,] arrExpanded = new T[rows0, rows1, rows2];
int i, j, k;
for (k = 0; k < rows0; k++)
{
for (j = 0; j < rows1; j++)
{
for (i = 0; i < rows2; i++)
{
T test = arr[i + j * rows2 + k * rows1 * rows2];
arrExpanded[k, j, i] = test;
}
}
}
return arrExpanded;
}
You could give this a go:
void Main()
{
int[,,] array3D = new int[,,]
{
{ { 1, 2 }, { 3, 4 }, {5,6 }, {7,8 } },
{ { 9, 10}, { 11, 12},{ 13,14} , {15,16 }},
{ { 17, 18}, { 19, 20},{ 21,22}, {23,24 } }
};
var flattened = array3D.Cast<int>().ToArray();
var restored = Expand(flattened, 3, 4);
}
public static T[,,] Expand<T>(T[] arr, int rows0, int rows1)
{
int length = arr.GetLength(0);
int rows2 = length / rows0 / rows1;
int x = 0;
T[,,] arrExpanded = new T[rows0, rows1, rows2];
for (int i = 0; i < rows0; i++)
{
for (int j = 0; j < rows1; j++)
{
for (int k = 0; k < rows2; k++)
{
T test = arr[x++];
arrExpanded[i, j, k] = test;
}
}
}
return arrExpanded;
}
It worked fine for me.
With a help of Linq OfType<T>(), it's easy to have int[] from any multidimensional array:
var result = source.OfType<int>().ToArray();
Demo:
using System.Linq;
...
int[,,] array3D = new int[,,] {
{ { 1, 2}, { 3, 4}, { 5, 6}, { 7, 8 } },
{ { 9, 10}, { 11, 12}, { 13, 14}, {15, 16 } },
{ { 17, 18}, { 19, 20}, { 21, 22}, {23, 24 } },
};
var result = array3D.OfType<int>().ToArray();
Console.Write(string.Join(", ", result));
Outcome:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24
We can use modulo arithmetics to Expand array back:
private static T[,,] Expand<T>(T[] value, int length1, int length2, int length3) {
T[,,] result = new T[length1, length2, length3];
for (int i = 0; i < value.Length; ++i) {
int r = i / (length3 * length2);
int c = i / length3 % length2;
int h = i % length3;
result[r, c, h] = value[i];
}
return result;
}
E.g.
int[,,] back = Expand(result, 3, 4, 2);
To flatten a multidimensional array just use Cast<T>().ToArray().
var d3 = new int[,,]
{
{ { 1, 2 }, { 3, 4 }, {5,6 }, {7,8 } },
{ { 9, 10}, { 11, 12},{ 13,14} , {15,16 }},
{ { 17, 18}, { 19, 20},{ 21,22}, {23,24 } }
};
var d1 = d3.Cast<int>().ToArray();
Console.WriteLine(string.Join(" ", d1));
Gives:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
To expand use this:
static int[,,] Expand(int[] array, int size2, int size3)
{
var size = new[] { array.Length / size2 / size3, size2, size3 };
var res = Array.CreateInstance(typeof(int), size);
for (var i = 0; i < array.Length; i++)
res.SetValue(array[i], GetMultidimensionalIndex(i, size));
return (int[,,])res;
}
static int[] GetMultidimensionalIndex(int index, int[] size)
{
var factors = size.Select((item, i) => size.Skip(i).Aggregate((a, b) => a * b)).ToArray();
var factorsHelper = factors.Zip(factors.Skip(1).Append(1), (Current, Next) => new { Current, Next }).ToArray();
return factorsHelper.Select(item => index % item.Current / item.Next).ToArray();
}
Usage:
var d3 = new int[,,]
{
{ { 1, 2 }, { 3, 4 }, {5,6 }, {7,8 } },
{ { 9, 10}, { 11, 12},{ 13,14} , {15,16 }},
{ { 17, 18}, { 19, 20},{ 21,22}, {23,24 } }
};
Console.WriteLine("Original:");
Print3DArray(d3);
var flat = d3.Cast<int>().ToArray();
Console.WriteLine("Flat:");
Console.WriteLine(string.Join(" ", flat));
var expanded = Expand(flat, d3.GetLength(1), d3.GetLength(2));
Console.WriteLine("Expanded:");
Print3DArray(expanded);
with helper method:
static void Print3DArray(int[,,] array)
{
Console.WriteLine("{");
for (int i = 0; i < array.GetLength(0); i++)
{
Console.Write(" {");
for (int j = 0; j < array.GetLength(1); j++)
{
Console.Write(" {");
for (int k = 0; k < array.GetLength(2); k++)
{
Console.Write($" {array[i, j, k]}");
}
Console.Write(" }");
}
Console.WriteLine(" }");
}
Console.WriteLine("}");
}
Gives:
Original:
{
{ { 1 2 } { 3 4 } { 5 6 } { 7 8 } }
{ { 9 10 } { 11 12 } { 13 14 } { 15 16 } }
{ { 17 18 } { 19 20 } { 21 22 } { 23 24 } }
}
Flat:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Expanded:
{
{ { 1 2 } { 3 4 } { 5 6 } { 7 8 } }
{ { 9 10 } { 11 12 } { 13 14 } { 15 16 } }
{ { 17 18 } { 19 20 } { 21 22 } { 23 24 } }
}

Initialize 2 dimensional array inside nested loop

I am working on an issue where i need to Declare a two - dimensional array named multiplicationTable
that contains 4 elements by 4 elements.Initialize it in
a nested loop to contain elements that equal to the value
that is the product of the two index values for
each element. In a second nested loop, display the values
in the console output, with column elements separated with
commas, and row elements separated with carriage returns. This is what i have so far, for some reason can't wrap my brain around the solution! Any help would be appreciated!.
double[,] multiplicationTable = new double[4, 4];// { {1,2,3,4 }, {5,6,7,8 }, {9,10,11,12 }, {13,14,15,16 } };
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
double d = multiplicationTable[i, j];
if (j < multiplicationTable.GetLength(1) - 1)
{
Console.Write(d + ",");
}
else
{
Console.Write(d);
}
}
Console.Write("\n");
}
Console.ReadKey();
double[,] multiplicationTable = new double[4, 4];
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
multiplicationTable[i, j] = i * j;
double d = multiplicationTable[i, j];
if (j < multiplicationTable.GetLength(1) - 1)
{
Console.Write(d + ",");
}
else
{
Console.Write(d);
}
}
Console.Write("\n");
}
Console.ReadKey();
Why not try to solve this with String.Join method? It is easy to use and will save you a lot of if-else statements. Here it is how it will look like with this method:
double[,] multiplicationTable = new double[4, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
var temp = new string[4];
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
temp[j] = multiplicationTable[i, j].ToString();
}
Console.WriteLine(string.Join(",", temp));
}
Console.ReadKey();
double[,] multiplicationTable = new double[4, 4];
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
var temp = new string[multiplicationTable.GetLength(0)];
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
multiplicationTable[i, j] = i * j;
temp[j] = multiplicationTable[i, j].ToString();
}
Console.WriteLine(string.Join(",", temp));
}

How to transpose matrix?

I have made 8x8 matrix using c#, and now I need to transpose the matrix. Can you help me to transpose the matrix?
This is my matrix
public double[,] MatriksT(int blok)
{
double[,] matrixT = new double[blok, blok];
for (int j = 0; j < blok ; j++)
{
matrixT[0, j] = Math.Sqrt(1 / (double)blok);
}
for (int i = 1; i < blok; i++)
{
for (int j = 0; j < blok; j++)
{
matrixT[i, j] = Math.Sqrt(2 / (double)blok) * Math.Cos(((2 * j + 1) * i * Math.PI) / 2 * blok);
}
}
return matrixT;
}
public double[,] Transpose(double[,] matrix)
{
int w = matrix.GetLength(0);
int h = matrix.GetLength(1);
double[,] result = new double[h, w];
for (int i = 0; i < w; i++)
{
for (int j = 0; j < h; j++)
{
result[j, i] = matrix[i, j];
}
}
return result;
}
public class Matrix<T>
{
public static T[,] TransposeMatrix(T[,] matrix)
{
var rows = matrix.GetLength(0);
var columns = matrix.GetLength(1);
var result = new T[columns, rows];
for (var c = 0; c < columns; c++)
{
for (var r = 0; r < rows; r++)
{
result[c, r] = matrix[r, c];
}
}
return result;
}
}
And that is how to call it:
int[,] matris = new int[5, 8]
{
{1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 },
{9 , 10, 11, 12, 13, 14, 15, 16},
{17 , 18, 19, 20, 21, 22, 23, 24},
{25 , 26, 27, 28, 29, 30, 31, 32},
{33 , 34, 35, 36, 37, 38, 39, 40},
};
var tMatrix = Matrix<int>.TransposeMatrix(matris);
Your matrix is not a "perfect square" one. You need a result (transposedMatris) matrix. If your matrix were a perfect square one it would be enough to swap(a[i, j], a[j, i]) on the same matrix.
Generic type class has static method and the method should be called as below.
int[,] transposedMatris = Matrix.TransposeMatrix<int>(matris);
dumpMatrix(transposedMatris);
Dump the transposed matrix on console.
// Using Generics (dump string, integer, decimal, string)
public static void dumpMatrix<T>(T[,] a)
{
int m = a.GetLength(0);
int n = a.GetLength(1);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(a[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Transposed matrix dump:
1 9 17 25 33
2 10 18 26 34
3 11 19 27 35
4 12 20 28 36
5 13 21 29 37
6 14 22 30 38
7 15 23 31 39
8 16 24 32 40
I am not süre but you need to rotate an image clockwise 90 degrees follow below steps.
Step 1: Transpose Matrix
Step 2: Flip horizontally
int[,] a = new int[5, 5] {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
int m = a.GetLength(0);
int n = a.GetLength(1);
//dumpMatrix(a);
// Step 1: Transpose Matrix
int temp = 0;
for (int i = 0; i < m; i++)
{
for (int j = i; j < n; j++)
{
temp = a[i, j];
a[i, j] = a[j, i];
a[j, i] = temp;
}
}
//Console.WriteLine("Step 1: Transpose Matrix");
//dumpMatrix(a);
// Step 2: Flip horizontally
for (int i = 0; i < m; i++)
{
for (int j = 0; j < (n/2); j++)
{
temp = a[i, j];
a[i, j] = a[i, n - 1 - j];
a[i, n - 1 - j] = temp;
}
}
//Console.WriteLine("Step 2: Flip horizontally");
//dumpMatrix(a);

Using method add all numbers of the array

Am I doing it right? I am trying to add each number of this 2 dimensional array and display the total. I think I am on the right track but well I am stuck if anyone could help me I be very thankful.
int[,] A = new int[3, 4]
{
{ 4, -5, 12, -2},
{ -9, 15, 19, 6},
{ 18, -33, -1, 7}
};
private void TotArray(int[,] array)
{
int sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sum += A[i, j];
}
}
}
private void button1_Click(object sender, EventArgs e)
{
TotArray(A);
}
You are ignoring the sum variable, you should return it from your method.other than that your method looks fine.Also remember you can always use LINQ for that kind of operations:
var sum = A.OfType<int>().Sum();
If you want to display the sum at the end:
int[,] A = new int[3, 4]
{
{ 4, -5, 12, -2},
{ -9, 15, 19, 6},
{ 18, -33, -1, 7}
};
private void TotArray(int[,] array)
{
int sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sum += A[i, j];
}
}
MessageBox.Show("The sum of the array is " + sum.ToString() + "."); //Show the sum
}
private void button1_Click(object sender, EventArgs e)
{
TotArray(A);
}

Sum, Subtract and Multiply arrays

I've got the following arrays:
int[,] myArray1 = new int[2, 3] { { 1, 2, 3 }, { 4, 6, 8 } };
int[,] myArray2 = new int[2, 3] { { 6, 4, 3 }, { 8, 2, 8 } };
What I'd like to know how to do is:
Create a new array with the sum of myArray1 and myArray2
Create a new array with the subtraction of myArray1 and myArray2
Create a new array with the multiplication of myArray1 and myArray2
Result of sum would be:
int[,] myArray3 = new int[2, 3] { { 7, 6, 0 }, { -4, 4, 0 } };
Result of subtraction would be:
int[,] myArray3 = new int[2, 3] { { 5, 2, 6 }, { 12, 8, 16 } };
Result of multiplication would be:
int[,] myArray3 = new int[2, 3] { { 6, 8, 9 }, { 32, 12, 64 } };
Can this be done similar to printing out the arrays, with for loops? I tried looking for examples but found none that I could use for my specific problem.
int[,] a3 = new int[2,3];
for(int i = 0; i < myArray1.GetLength(0); i++)
{
for(int j = 0; j < myArray1.GetLength(1); j++)
{
a3[i,j] = myArray1[i,j] + myArray2[i,j];
a3[i,j] = myArray1[i,j] - myArray2[i,j];
a3[i,j] = myArray1[i,j] * myArray2[i,j];
}
}
need to store a3 before doing a new calculation obviously
For Sum:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = myArray1[i, j] + myArray2[i, j];
}
}
For Subtraction:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = myArray2[i, j] - myArray1[i, j];
}
}
For Multiplication:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
myArray3[i, j] = A[i, j] * B[i, j];
}
}
Yes this would be done exactly like printing out the arrays with for loops
c# has foreach loops which would be even easier to use
Note: I get the idea this is for homework so I'm not going to give a 100% conclusive end all be all answer.
int[,] myArray1 = new int[2, 3] { { 1, 2, 3 }, { 4, 6, 8 } };
int[,] myArray2 = new int[2, 3] { { 6, 4, 3 }, { 8, 2, 8 } };
foreach (int[] a1 in myArray1)
{
foreach(int i in a1)
{
//operation here
//you get the idea
}
}
If you want to do array manipulation faster use the C# Parallel.For loop from System.Threading.Tasks:
For simple arithmetic parallelizing the outer loop is much faster than not on a modern PC processor. For more complex operations, or for small array sizes, the parallel version can be slower for various reasons.
Thus, use a stopwatch to time your matrix operations, and use the fastest solution. Parallelization makes doing array / image processing in C# much faster if implemented right.
Beware of overflowing your datatypes after arithmetic operations and also sharing variables between multiple threads (see System.Threading.Interlocked for help with that)...
Subtraction below. Similar for addition and multiplication:
Parallel.For(0, array.GetLength(1), y=>
{
for (int x = 0; x < array.GetLength(0); x++)
{
difference[x,y] = minuend[x,y] - subtrahend[x,y];
}
}
});
If you want to use a for loop, you can iterate through the rows/columns of the multi-d array as follows:
for (int i = 0; i < myArray1.GetLength(0); i++)
{
for (int j = 0; j < myArray1.GetLength(1); j++)
{
// Here, you can access the array data by index, using i and j.
// Ex, myArray1[i, j] will give you the value of 1 in the first iteration.
}
}
Note: When you pass a value into the Array's GetLength method, it represents the dimension of the array. See http://msdn.microsoft.com/en-us/library/system.array.getlength.aspx

Categories

Resources