
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
Print Identity Matrix in Swift
In this article, we will learn how to write a swift program to print an identity matrix. Identity matrix is a square matrix in which the main diagonal elements contain only one and the rest of the elements are 0. For example ?
$\mathrm{Matrix\:=\:\begin{bmatrix}1 & 0 & 0 & 0 & 0 \newline0 & 1 & 0 & 0 & 0 \newline0 & 0 & 1 & 0 & 0\newline0 & 0 & 0 & 1 & 0\newline0 & 0 & 0 & 0 & 1\end{bmatrix}}$
Algorithm
Step 1 ? Create a function.
Step 2 ? In this function, use nested for loop to irate through each row and column.
Step 3 ? Check if the rows and columns are equal, then print 1. Otherwise, print 0.
Step 4 ? Declare a variable to store the size of the array.
Step 5 ? Call the function and pass the array size as a parameter in it.
Step 6 ? Print the output.
Example
Following Swift program to print an identity matrix
import Foundation import Glibc // Function to create identity matrix func createIdentityMatrix(len:Int) { for x in 0..<len { for y in 0..<len { if (x == y) { print("1", terminator:" ") } else{ print("0", terminator:" ") } } print("\n") } } // Size of the matrix var size = 6 print("Identity Matrix: ") // Calling the function createIdentityMatrix(len:size)
Output
Identity Matrix: 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1
Here in the above code, we create a function to print the identity matrix. As we know, the main diagonal of the identity matrix contains 1 and the rest elements are 0. So we use nested for loops to iterate through each row and column and print 1 if x == y means the element is the main diagonal element. Otherwise, print 0.
Conclusion
Therefore, this is how we can print the identity matrix. The inverse of the identity matrix is the same as the given identity matrix and the determinant of the identity matrix is 1.