Press "Enter" to skip to content

Transpose Matrix Example Using PHP

The transpose of a matrix is a new matrix whose rows are columns of an original matrix. In this tutorial, you will learn through an example to implement transpose of a matrix using the PHP program. Here is an example of the transpose of a matrix:

Original Matrix – Transpose of a Matrix

1 2 3 1 4 7 
4 5 6 2 5 8
7 8 9 3 6 9

 

PHP Program to Implement The Transpose of a Matrix

<html>
    <body>
        <?php
echo "<b>The matrix is given below:-</b>"."<br>";
$a=array(array());//declaring the array
$rows=4; //number of rows
$cols=4; //number of columns
$m=1;
for($i=0;$i<$rows;$i=$i+1)
{
    for($j=0;$j<$cols;$j=$j+1)
    {
        $a[$i][$j]=$m;
        echo $a[$i][$j]." ";
        $m=$m+1;
    }
    echo "<br>";
}
echo "<b>The transpose of a matrix is given below:-</b>"."<br>";
for($i=0;$i<$rows;$i=$i+1)
{
    for($j=0;$j<$cols;$j=$j+1)
    {
        $a[$i][$j]=$a[$j][$i]; //assigning the values of elements of each column to each row
        echo $a[$i][$j]." ";
    }
    echo "<br>"; //here this is creating a new line 
}
        ?>
    </body>
</html>

Output:

The matrix is given below:-
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The transpose of a matrix is given below:-
1 5 9 13
5 6 10 14
9 10 11 15
13 14 15 16

Vinish Kapoor

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *