Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

Search This Blog

Surrounded matrix


Surrounded matrix

With a given matrix A (size m x n) create a matrix B (size m+2 x n+2) so that the matrix A is surrounded by ones:

A = [1 2 3
        3 2 1]

B = [1 1 1 1 1
       1 1 2 3 1
       1 3 2 1 1
       1 1 1 1 1]
or

A = 4

B = [ 1 1 1
         1 4 1
         1 1 1]


MATLAB CODE:


clc
m=input ('no. of rows');
n=input('Enter no of columns:');
x=input('Enter the matrix:');
Y=[];
for i=1:m+2
    for j=1:n+2
        if(i==1 || j==1||i==m+2 ||j==n+2)
            Y(i,j)=1;
     
        else
            Y(i,j)=x(i-1,j-1);
        end
    end
end

Explanation:




OUTPUT:


JAVA Program:

import java.io.*;
class Dup
{
public static void main(String args[])throws IOException
{
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the no. of rows:");
int m=Integer.parseInt(r.readLine());
System.out.println("Enter the no. of columns:");
int n=Integer.parseInt(r.readLine());
int a[][]=new int[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.println("Enter the number corresponding to array index"+i+j);
a[i][j]=Integer.parseInt(r.readLine());
}
}
int y[][]=new int[m+2][n+2];
for(int i=0;i<(m+2);i++)
{
for(int j=0;j<(n+2);j++)
{
if(i==0 || j==0 || i==m+1 ||j==n+1)
{
y[i][j]=1;
}
else
{
y[i][j]=a[i-1][j-1];
}
}
}
for(int i=0;i<m+2;i++)
{
for(int j=0;j<n+2;j++)
{
System.out.print(y[i][j]+" ");
}
System.out.println();
}
}
}
Output:


No comments

Popular Posts

Followers