Search code examples
carrayssortingdynamic-arrays

Merging entries of two arrays as the even and odd entries of another array.


I've got a function thats able to produces 2 arrays, one when the index 'i' is even and one when the index 'i' is odd, so I end up with two arrays. The even 'i' array is called W_e and made of N elements, the odd 'i' array is called W_o and also made of N elements.

I now need to be merge these two arrays into another array Wn (which has 2*N elements) such that it looks like Wn=[W_e[0],W_o[0],W_e[1],W_o[1],...,W_e[N-1],W_o[N-1]] but I'm not sure how to do it. I tried to use nested loops but it didn't work. The arrays W_e and W_o are produced correctly according to my calculations, I'm just unable to combine the entries into one array.

This is what I have so far. I have not done anything in the main function except call the function which is giving me trouble "double *MakeWpowers(int N);". Please keep in mind this works for N>2, I have not yet dealt with N=1 or N=2.

Any help will be greatly appreciated. Thank you!!

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>

#define pi 4*atan(1)

double *MakeWpowers(int N);
void print_vector(double *x,int N);
double *make_vector(double *x,int N);

int main(void)
{   int N;
double *Wn;
printf("\n Please enter the size of the NxN matrix:\n");
scanf("%d",&N);
Wn=MakeWpowers(N);
//print_vector(Wn,N);
free(Wn);
return(0);
}

double *MakeWpowers(int N)
{
double *Wn,*W_e,*W_o;
int i,j;

Wn=make_vector(Wn, 2*N);
W_e=make_vector(W_e, N);
W_o=make_vector(W_o, N);


for(i=0;i<=N-1;i++)
{
    if(i%2==0)

    {
        W_e[i]=cos((2*i*pi)/N);
    }
    else 
    {
            W_o[i]=sin((2*i*pi)/N);
    }

}

printf("\nThis is the even vector W_e:\n");
print_vector(W_e, N);
printf("\nThis is the odd vector W_o:\n");
print_vector(W_o, N);


for(j=0;j<2*N;j++)
{
    if(j%2==0)
    {Wn[j]=W_e[i];}
        //++i;}
    else 
    {Wn[j]=W_o[i];}
        //++i;}
    printf("\nthis is Wn:\n\n");
    print_vector(Wn, 2*N);
 //Wn[j]=W_o[i];
 //j++;
}

return(Wn);
   }
 void print_vector(double *x,int N)
{
int i;
for (i=0; i<N; i++) 
{
    printf ("%9.4f  \n", x[i]);
}
printf("\n"); 
}


double *make_vector(double *x,int N)
{   int i;
double xi;

x=(double *)malloc((N)*sizeof(double));

for(i=0;i<N;i++)
{
    x[i]=(double)xi;
}
return(x);
}

Solution

  • Here's the general logic to it:

    LET a, b, merge BE ARRAYS
    FOR k IN 0..length(a)
        merge[2*k]   = a[i]
        merge[2*k+1] = b[i]
    RETURN merge
    

    a makes the even entries (2k), b the odd ones (2k+1).