Transpose non square matrices C# - c#

I can transpose a square matrix, but now I'd like to transpose a non square matrix (in my code 3*2) with user input.
Other sources recommended me to create a new matrix first, which I have done. I manage to make the matrix, but when transposing, it stops from the 4th value.
I have looked at other topics but I can't find the error. Here is my code so far, can someone tell me where I went wrong?
Thanks!
//const
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write("Enter num: ");
matrix1[i, j] = int.Parse(Console.ReadLine());
}
}
//output
Console.WriteLine("Eerste matrix: ");
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write(matrix1[i, j] + " ");
}
Console.WriteLine(" ");
}
//transposed matrix
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
matrix2[j, i] = matrix1[j, i];
Console.Write(matrix2[j, i] + " ");
}
Console.WriteLine(" ");
}
This is what I get when running the program:
//output
Enter num: 1
Enter num: 2
Enter num: 3
Enter num: 4
Enter num: 5
Enter num: 6
first matrix:
1 2
3 4
5 6
transposed matrix:
1 3
2 4
//--->> Only went up to 4th value?

So, at the beginning you load a matrix with fields : "i,j" => "row, column"
On the last step, you try accessing the matrix with a "j,i" => "column, row" order.
You're inverting the i,j indexes.-
Let me help you by just changing the variable names :
//const
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column ++)
{
Console.Write("Enter num: ");
matrix1[row, column] = int.Parse(Console.ReadLine());
}
}
//output
Console.WriteLine("Eerste matrix: ");
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{`enter code here`
Console.Write(matrix1[row, column] + " ");
}
Console.WriteLine(" ");
}
//transposed matrix
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{
matrix2[column, row] = matrix1[row, column];
Console.Write(matrix2[column, row] + " ");
}
Console.WriteLine(" ");
}
// EDIT : actually noticed the sample didn't traspose it properly. fixed it.

Replace
matrix2[j, i] = matrix1[j, i];
with
matrix2[j, i] = matrix1[i, j];
This way a row number of matrix1 becomes a column number for matrix2 - i.e. the matrix gets transposed.

If you combine the other two answers, you will have a complete picture:
This line is wrong and will give you an IndexOutOfRangeException:
matrix2[j, i] = matrix1[j, i];
In order to transpose you need to flip the indices:
matrix2[j, i] = matrix1[i, j];
Another problem is that when you print the matrix, you switch rows and columns.
It's easier to just extract the code for each functionality into a separate method.
Also, using the names i and j can be confusing. They look alike and they don't convey their meaning. When working with matrices, I like to use r and c (or row and column)
void PrintMatrix(int[,] m)
{
int rows = m.GetLength(0);
int columns = m.GetLength(1);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
Console.Write(m[r, c] + " ");
}
Console.WriteLine();
}
}
int[,] TransposeMatrix(int[,] m)
{
int rows = m.GetLength(0);
int columns = m.GetLength(1);
int[,] transposed = new int[columns, rows];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
transposed[c, r] = m[r, c];
}
}
return transposed;
}
Then the last part of your code becomes simply:
PrintMatrix(matrix1);
Console.WriteLine();
int[,] matrix2 = TransposeMatrix(matrix1);
PrintMatrix(matrix2);

Related

Delete border of matrix

I have a 2d array[,] and I need to delete the border of it (or create a new array without it). I tried everything I thought of and nothing worked since I don't usually work with 2d arrays. Help please?
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7
becomes:
6 7
1 2
Queue<int> numbers = new Queue<int>();
int[,] b = new int[4, 4];
for (int i = 0; i < b.GetLength(0); i++)
{
for (int j = 0; j < b.GetLength(1); j++)
{
int x = int.Parse(Console.ReadLine());
b[i, j] = x;
}
}
int rows = b.GetLength(0);
Console.WriteLine("Number of rows: "+rows);
int columns = b.GetLength(1);
Console.WriteLine("Number of columns: " + columns);
int[,] arrayUpdated = new int[columns - 2,rows - 2];
for (int n = 0; n < b.GetUpperBound(1); n++)
{
for (int i = 0; i < b.GetUpperBound(0); i++)
{
arrayUpdated[i, n] = b[i, n];
Console.WriteLine(arrayUpdated[i, n]);
}
}
public static T[,] RemoveBorders<T>(T[,] source)
{
//index of last item, not number of items
var ROW = source.GetUpperBound(0);
if (ROW < 2) throw new ArgumentException("source array is not tall enough");
var COL = source.GetUpperBound(1);
if (COL < 2) throw new ArgumentException("source array is not wide enough");
var result = new T[ROW - 1, COL - 1];
for (int r = 1; r < ROW; r++)
{
for (int c = 1; c < COL; c++)
{
result[r-1, c-1] = source[r, c];
}
}
return result;
}
https://dotnetfiddle.net/dtUpRA
You would use it in the code in the question like this:
int[,] arrayUpdated = RemoveBorders(b);

How can I display two matrices side by side in c#?

I made a program that calculates multiplication of matrices in c#. Is it possible to show the result like this?
(Matrix1) * (Matrix2) = (Result)
My code :
using System;
namespace MatrixMultiplication;
{
class MainClass
{
static void ShowMatrix(int [,] m){
for (int i = 0; i < m.GetLength(0); i++) {
for (int j = 0; j < m.GetLength(1); j++) {
Console.Write(m[i,j]+" ");
}
Console.WriteLine ();
}
}
static int[,] MultiplyMatrices(int [,] a , int [,] b){
int[,] result = new int[a.GetLength(0),a.GetLength(1)];
for (int i = 0; i < a.GetLength(0);i++) {
for (int j = 0; j < a.GetLength(0); j++) {
for (int k = 0; k < a.GetLength(1); k++) {
result [i, k] += a [i, j] * b [j, k];
}
}
}
return result;
}
public static void Main (string[] args)
{
int rows,columns;
Console.WriteLine ("Rows : ");
rows = Convert.ToInt32 (Console.ReadLine());
Console.WriteLine ("Columns : ");
columns = Convert.ToInt32(Console.ReadLine());
int [,] lhsm = new int[rows,columns];
int [,] rhsm = new int[rows,columns];
int [,] result = new int[rows,columns];
Console.WriteLine ("Enter Elements of the First matrix : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
Console.WriteLine ("F[{0}][{1}] : ",i,j);
lhsm [i,j] = Convert.ToInt32 (Console.ReadLine ());
}
}
Console.WriteLine ("Enter Elements of the Second matrix : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
Console.WriteLine ("L[{0}][{1}] : ",i,j);
rhsm [i,j] = Convert.ToInt32 (Console.ReadLine ());
}
}
result = MultiplyMatrices (lhsm, rhsm);
Console.Clear ();
Console.WriteLine ("Matrix 1 : ");
ShowMatrix (rhsm);
Console.WriteLine ("Matrix 2 : ");
ShowMatrix (lhsm);
Console.WriteLine ("Result : ");
ShowMatrix (result);
}
}
}
One way to do this using SetCursorPosition would be to modify your ShowMatrix method to first store the starting position of the cursor, and then reset the cursor to the original "left" value while incrementing the "top" value for each row. Note I'm also using a variable to track the column width, which I'm using to ensure that each column is the same width for each grid. This value may need to be increased if you use large numbers:
const int maxColumnWidth = 5;
static void ShowMatrix(int[,] matrix, string name)
{
var startColumn = Console.CursorLeft;
var startRow = Console.CursorTop;
Console.SetCursorPosition(startColumn, startRow);
Console.Write($"{name}:");
Console.SetCursorPosition(startColumn, ++startRow); // <-- Note this increments the row
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j].ToString().PadRight(maxColumnWidth));
}
Console.SetCursorPosition(startColumn, ++startRow); // <-- increment row again
}
}
Then, when you call the method, you can reset the cursor position back to the top and one space more to the right from the last grid that was shown (by multiplying the number of columns by the column width constant):
// code to get matrix values omitted
result = MultiplyMatrices(lhsm, rhsm);
Console.Clear();
// Capture initial cursor values
var cursorTop = Console.CursorTop;
var cursorLeft = Console.CursorLeft;
ShowMatrix(lhsm, "Matrix 1");
// Move cursor just to the right of the previous matrix, and at the same top
cursorLeft += lhsm.GetLength(1) * maxColumnWidth + 1;
Console.SetCursorPosition(cursorLeft, cursorTop);
ShowMatrix(rhsm, "Matrix 2");
// Move cursor just to the right of the previous matrix, and at the same top
cursorLeft += rhsm.GetLength(1) * maxColumnWidth + 1;
Console.SetCursorPosition(cursorLeft, cursorTop);
ShowMatrix(result, "Result");
// Move cursor back to the beginning, and just underneath the previous matrix
Console.SetCursorPosition(0, cursorTop + result.GetLength(0) + 1);
GetKeyFromUser("\nDone! Press any key to exit...");
}

How to extract specific column from 2D array

I have an array and i want to extract specific column from it, let's say the 3rd column only.
Example:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
What is want is to extract 3rd column and display only:
3
3
3
3
This is my code where i am able to create a dynamic array specified by the user:
int r;
int c;
Console.Write("Enter number of rows: ");
r = (int)Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number of columns: ");
c = (int)Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[r, c];
/*Insert Values into Main Matrix
--------------------------------------------------------------------------------*/
for (int row = 0; row < r; row++)
{
for (int col = 0; col < c; col++)
{
Console.Write("Enter value for matrix[{0},{1}] = ",row, col);
matrix[row, col] = (int)Convert.ToInt32(Console.ReadLine());
}
}
/*Print and show initial Matrix
--------------------------------------------------------------------------------*/
Console.WriteLine("Your matrix is,");
for (int row = 0; row < r; row++)
{
for (int col = 0; col < c; col++)
{
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}
/*Fixing first 2 columns
--------------------------------------------------------------------------------*/
int startingMatrixCols = 2;
Console.WriteLine("Fixed first 2 columns:");
for (int row = 0; row < r; row++)
{
for (int col = 0; col < startingMatrixCols; col++)
{
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}
var column = 2; // your expected column
//if it needs to be dynamic, you can read it from user entry
// Console.Write("Enter expected column: ");
// column = int.Parse(Console.ReadLine()); //enhance with error checks
for (int row = 0; row < r; row++)
{
Console.Write(matrix[row, column] + " ");
}
Console.Write("Enter the column number to display ");
int displayColNo = (int)Convert.ToInt32(Console.ReadLine());
/*If displayColNo=3 it displays only 3rd column numbers*/
for (int row = 0; row < r; row++)
{
Console.Write(matrix[row, displayColNo]);
Console.WriteLine();
}

Read matrix elements in row wise

I am writing C# program for a matrix.when I enter matrix inputs from console, each element is coming in the separate row.But, I want to read row elements in a single line.
This is my code
Console.WriteLine("Enter the matrix");
int n= Convert.ToInt32(Console.ReadLine());
int[ , ] matrix=new int[n,n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
matrix[i,j]=Convert.ToInt32(Console.ReadLine());
// Console.Write("\t");
}
}
present I am getting like
1
2
3
4
But, I want like
1 2
3 4
Help me.
If you want to read one row in one line, you can ask user to enter space-separated values like 1 2, 3 4 and read like this
Console.WriteLine("Enter the matrix size");
int n = Convert.ToInt32(Console.ReadLine());
//add size and other validation if required
int[,] matrix = new int[n, n];
Console.WriteLine("Enter your values separated by space.");
for (int i = 0; i < n; i++)
{
var values = (Console.ReadLine().Split(' '));
for (int j = 0; j < n; j++)
{
matrix[i, j] = int.Parse(values[j]);
}
}
//to write
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
You can enter the entire line and do the following:
for(int i=0; i<n; i++){
var input = Console.ReadLine().Split(' ').Select(t => int.Parse(t)).ToArray();
for (int j = 0 ; j < n ; j++){
matrix[i, j] = input[j];
}
}
Console.WriteLine("Enter the matrix");
int n= Convert.ToInt32(Console.ReadLine());
int[ , ] matrix=new int[n,n];
for(int i=0; i<n; i++){
string line = Console.ReadLine();
string[] elements = line.Split(' ');
for(int j=0; j<n || j < elements.Length; j++){
matrix[i,j]=Convert.ToInt32(elements[j]);
}
}
Please look same question
In your situation :
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j + 2){
string input = Console.ReadLine();
string[] split = input.Split(' ');
int firstNumber = Int32.Parse(split[0]);
int secondNumber = Int32.Parse(split[1]);
matrix[i,j] = firstNumber ;
matrix[i,(j+1)] = secondNumber ;
}
}

Creating mutidimensional array consisting of asterisks

I am new to programming and I want my program to run a table consisting of stars(asterisks). E.g. table 4x3 has 4x3 stars. But my initial problem is that I do not know how to implement a multidimensional array in such a way that I just need to change the initial value of rows and columns in order to create more or less stars.
So: here is my code at the moment:
using System;
namespace ConsoleApplication1
{
class Multidimensional_array
{
static void Main(string[] args)
{
int arrayRows = 4;
int arrayCols = 3;
int[,] arrayTimes;
arrayTimes = new int [arrayRows, arrayCols];
//String star = "*";
for( int i = 0; i <= arrayRows; i++) {
for( int j = 0; j <= arrayCols; j++) {
//Console.WriteLine("*");
//arrayTimes[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.ReadLine();
}
}
}
So I just want that if I change the int arrayRows to 5 and int arrayCols to 5 then I receive a star table of 5x5. T
I think you're very close, you're just using the wrong data type for your array, haven't assigned the * to each position in said array, and your current code would give you an ArrayIndexOutOfBounds exception. You may have 4 rows and 3 columns, but array indices are zero-based, meaning when you access positions 1, 2, 3, etc. you use an index of 0, 1, 2, etc. respectively.
So, since you want to store the text "*", you should use a char[,] or a string[,] for your multi-dimensional array. I've chosen char[,] for this:
int arrayRows = 4;
int arrayCols = 3;
char[,] arrayTimes = new char[arrayRows, arrayCols];
const char star = '*';
// Set it up
for (int i = 0; i <= arrayRows - 1; i++)
{
for (int j = 0; j <= arrayCols - 1; j++)
{
arrayTimes[i, j] = star;
}
}
// Print it out
for (int i = 0; i <= arrayRows - 1; i++)
{
for (int j = 0; j <= arrayCols - 1; j++)
{
Console.Write(arrayTimes[i, j]);
}
Console.WriteLine();
}
Working ideone sample
Simple solution
static void Main(string[] args)
{
// Get the number of rows
Console.WriteLine("Enter the number of rows:");
int arrayRows = Convert.ToInt32(Console.ReadLine());
// Get the number of columns
Console.WriteLine("Enter the number of columns:");
int arrayCols = Convert.ToInt32(Console.ReadLine());
// For each item in the row
for (int i = 0; i < arrayRows; i++)
{
// For each item in the column
for (int j = 0; j < arrayCols; j++)
{
// Show a star
Console.Write("*");
}
// End the line
Console.WriteLine("");
}
// Read the line to stop the app from closing
Console.ReadLine();
}
If you want to store the stars
static void Main(string[] args)
{
// Get the number of rows
Console.WriteLine("Enter the number of rows:");
int arrayRows = Convert.ToInt32(Console.ReadLine());
// Get the number of columns
Console.WriteLine("Enter the number of columns:");
int arrayCols = Convert.ToInt32(Console.ReadLine());
// Create an array
char[,] arrayTimes = new char[arrayRows, arrayCols];
char star = '*';
// For each item in the row
for (int i = 0; i < arrayRows; i++)
{
// For each item in the column
for (int j = 0; j < arrayCols; j++)
{
// Show a star
arrayTimes[i, j] = star;
}
}
// Read the line to stop the app from closing
Console.ReadLine();
}
This do what you want,
int arrayRows = 2;
int arrayCols = 2;
char[,] arrayTimes;
arrayTimes = new char[arrayRows, arrayCols];
//String star = "*";
for (int i = 0; i < arrayRows; i++)
{
for (int j = 0; j < arrayCols; j++)
{
arrayTimes[i, j] = '*';
Console.Write("{0}",arrayTimes[i, j]);
}
Console.WriteLine();
}
Console.ReadKey();

Categories

Resources