Duplicate each element of a vector in MATLAB


Function related programs in MATLAB:

For an n-dimensional vector X, the function should return another 2n-dimension where each element is repeated twice.
 For example: if a=[2 3 4 5], after using the function, a=[2 2 3 3 4 4 5 5];
It should work with a vector of ANY random size.

CODE:

clc

x=input('Enter the array:');
Y=[];
for i=1:length(x)
    m=x(i);
    Y=[Y m m];
end
disp(Y)

Explanation:


    
Function:

function Y=myfun(x)
z=x;
Y=[];
for i=1:length(z)
    m=z(i);
    Y=[Y m m];
end
disp Y;
end

  Output:


JAVA Program:

import java.util.Scanner;
class Ta
{
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++)
{
System.out.println("Enter the number in array:");
a[i]=obj.nextInt();
}
for(int i=0;i<l;i++)
{
System.out.print(" ");
System.out.print(a[i]);
System.out.print(" ");
System.out.print(a[i]);
}
}

}

Output:


No comments