I want a image. Firstly I want to do fourier transform and get the magnitude and phase information. And then make a new random phase, finally use the changed random phase and original magnitude to make the inverse fourier transform. But I can not achieve it?

The code is shown here.

 img   = imread('flag.jpg');
 imafft = fftn(double(img));
 mag = abs(imafft);
 phi= angle(imafft);
 s= size (img);
 rand_phase= 4*pi*(rand(s(1),s(2))-0.5);
 newfft = mag.*exp(i*rand_phase);
 ima_out = ifft2(newfft); 
 axis image;
 title('Ramdom phase version');

The problem is in the sentence of newfft = mag.*exp(i*rand_phase); I do not know how to modify.

Who can help me? Thank you so much.

  • $\begingroup$ What exactly is "problem"? Do you get an error? $\endgroup$
    – Phonon
    Oct 14, 2014 at 18:18
  • $\begingroup$ Have you defined "i" as imaginary unit? In Matlab that should be either "j" or "1i". $\endgroup$
    – Hilmar
    Oct 14, 2014 at 19:13
  • $\begingroup$ You are right. Now my problem is the IFFT. What should I do to make a IFFT by using a mag and phase? Thank you so much $\endgroup$ Oct 15, 2014 at 11:52

2 Answers 2


You image is not an $N \times M$ matrix. It's actually an $N \times M \times 3$ array of numbers. I assume that's why you're using fftn instead of fft2 to take its Fourier transform.

You have to either

  1. convert your image to grayscale; or
  2. process each component independently.

To work get grayscale, we can naïvely average over the RGB colors like so:

img = mean(double(img),3)

To work with all three components independently, your phase array needs to have an extra dimension:

rand_phase= 4*pi*(rand(s(1),s(2), s(3))-0.5);
  • $\begingroup$ Thank you so much for your suggestion. That is the problem. I change to the gray scale, the problem is solved. But I have a new problem, I use the words of 'newfft = mag.*exp(i*rand_phase);' to do the IFFT, but the result does not come, what should I do to use a mag and phase to produce a new picture. Thanks a lot. $\endgroup$ Oct 15, 2014 at 11:51
  • $\begingroup$ @HEHongShen I am facing the same problem, were you able to solve it. Please help me if you solved it correctly. $\endgroup$
    – Ayush
    Dec 7, 2014 at 19:57

It should be newfft = mag.*exp(1i*rand_phase); instead of newfft = mag.*exp(i*rand_phase); 1i denotes the imaginary unit.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.