%% HW4 Program Function
% By: 105060012 張育菘

function [DFT1,DFT2] = tworealDFTs(x1,x2)
    N = length(x1);
    x = x1 + j*x2;
    DFT = fft(x, N);
    % DFT_circfold = conj(circfold(DFT, N));
    DFT_circfold = circfold(conj(DFT), N);
    DFT1 = 0.5*(DFT + DFT_circfold);
    DFT2 = (0.5*(DFT - DFT_circfold))/j;
end

%

function y = lin2circonv(h,x)
% Linear Convolution for any length of input signal
% N = max(length(h), length(x))
hxconv = conv(h, x);
N = max(length(h), length(x));

y = zeros(1, N);

for n = 1:1:N
    for len = -N:1:N
        if ((n+len*N) >= 1) && ((n+len*N) <= (length(hxconv)))
            y(n) = y(n) + hxconv(n+len*N);
        end
    end
end

%

function y=circfold(x,N)
    % Circular time reversal (folding)
    if length(x) > N; error('N < length(x)'); end 
    x=[x zeros(1,N-length(x))];
    n=(0:1:N-1);
    y=x(mod(-n,N)+1);
end