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

Search This Blog

Create diagonal matrix without using MATLAB built-in functions

Create diagonal matrix without using MATLAB built-in functions

MATLAB CODE:

clc
clear all
close all
v=input('Enter the array:');
y=[];
k=1;
for i=1:length(v)
    for j=1:length(v)
        if(i==j)
        y(i,j)=v(k);
        k=k+1;
        else
            y(i,j)=0;
        end
    end
end
disp(y);

Explanation:



Sample Output:



JAVA CODE:

import java.util.Scanner;
class Kuka
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the array length:");
int l=obj.nextInt();
int a[]=new int[l];
for(int i=0;i<l;i++)
{
a[i]=obj.nextInt();
}
int y[][]=new int[l][l];
int kl=0;
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i==j)
{
y[i][j]=a[kl];
kl=kl+1;
}
else
{
y[i][j]=0;
}
}
}
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
System.out.print(y[i][j]+" ");
}
System.out.println();
}
}
}

OUTPUT:


Try with other inputs :-)

No comments

Popular Posts

Followers