
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Transpose of a Matrix in Swift
In this article, we will learn how to write a swift program to find the transpose of a matrix. Transpose of a matrix is calculated by interchange the rows of a matrix into columns or columns of a matrix into rows. For example, we have the following matrix:
$$\mathrm{X\:=\:\begin{bmatrix} 13, & 59, & 32, & 67 \newline 23, & 56, &89, & 3 \newline 98, & 3, & 32, & 43 \newline 6, & 90, & 43, &23 \end{bmatrix}}$$
So the transpose of matrix X is ?
$$\mathrm{X^{T}\:=\:\begin{bmatrix} 13, & 23, & 98, & 6 \newline 59, & 56, & 3, & 90 \newline 32, & 89, & 32, & 43 \newline 67, & 3, & 43, &23 \end{bmatrix}}$$
So to find the transpose of a matrix in Swift we shape the elements of rows to columns of the matrix with the help of a temporary variable.
Algorithm
Step 1 ? Define the size of the matrix.
Step 2 ? Create a function that takes an array as an argument
Step 3 ? Run nested for loop.
Step 4 ? Inside nested for loop swap the rows with columns using the temp variable to find transpose.
let temp = C[x][y] C[x][y] = C[y][x] C[y][x] = temp
Step 5 ? Create a 3x3 matrix using an array.
Step 6 ? Pass the original matrix to the function as an argument
Step 7 ? Display output.
Example
In the following example, we find the transpose of a matrix.
import Foundation import Glibc // Size of the matrix var N : Int = 3 // Function to find the transpose of a matrix func transpose(A:[[Int]]) { var C:[[Int]] = A // finding transpose of a matrix by // swapping C[x][y] with C[y][x] for x in 0..<N { for y in (x+1)..<N { let temp = C[x][y] C[x][y] = C[y][x] C[y][x] = temp } } // Printing transpose of the matrix print("Transpose of Matrix A") for i in 0..<N { for j in 0..<N { print(C[i][j], terminator:" ") } print("\n") } } // Original matrix var X : [[Int]] = [[2,3,4], [4,5,6],[6,7,8]] print("Original Matrix A") for i in 0..<N { for j in 0..<N{ print(X[i][j], terminator:" ") } print("\n") } // Calling function transpose(A:X)
Output
Original Matrix A 2 3 4 4 5 6 6 7 8 Transpose of Matrix A 2 4 6 3 5 7 4 6 8
Here in the above code, a 3x3 matrix using a 2-D array. Now we create a function to find the transpose of the matrix. In this function, we swap the rows elements of the matrix to columns with the help of the temp variable to get the transpose of the given matrix.
Conclusion
So by swapping the rows with columns or columns with rows of a matrix we can find the transpose of the given matrix.