Bharat
Bharat

Reputation: 1082

Matlab fft function swapping indices

I've written a simple and very small Matlab code that calculates the Discrete Fourier Transfrom of a given array (or vector).

I worked it out manually and got an answer and my Matlab code also giving the same answer. But fft is giving an answer different from this by swapping indices. Here are the mannual calculations that I've done:

This is the first image

This is the second image:

This is the second image

This is the third image:

This is the third image

From those calculations it is clear that my answer would be {12, -3-3j, -2, -3+3j}

Here is the Matlab code that I've used:

clc;
clear all;
close all;
inp=[1,2,3,4];
j=sqrt(-1);
op=zeros(1,length(inp));
for k=1:length(inp)
    sigma=0;
    for n=1:length(inp)
        sigma=sigma+inp(n)*exp((j*2*pi*(k-1)*(n-1))/length(inp));
    end
    op(k)=sigma;
end
% Checking with fft
fft(inp)

Now I'm getting output as this:

Matlab Output

It is very much unexpected that I'm getting values swapped. It is swapping the indices 2 and 4.

Upvotes: 3

Views: 156

Answers (1)

Paul R
Paul R

Reputation: 212939

It looks like you have the wrong sign for your weights (which means you're probably doing an inverse FFT instead of a forward FFT - remember that for the forward transform the weights are exp(-j * theta)).

Change:

    sigma=sigma+inp(n)*exp((j*2*pi*(k-1)*(n-1))/length(inp));

to:

    sigma=sigma+inp(n)*exp(-(j*2*pi*(k-1)*(n-1))/length(inp));

Upvotes: 4

Related Questions