Inverse fourier transform by using a random phase and an original magnitude (matlab) 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); 
 figure(2);
 imagesc(abs(ima_out));
 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.
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 


convert your image to grayscale; or
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);