%% Write and Read Complex Numbers
% This example shows how to write and read complex numbers in binary files.
% The available precision values for fwrite do not explicitly support complex numbers. To store complex numbers in a file, separate the real and imaginary components and write them separately to the file. There are two ways to do this:
% Write all real components followed by all imaginary components
% Interleave the components
% Use the approach that allows you to read the data in your target application.
%% Separate Real and Imaginary Components
% Create an array that contains complex values.

nrows = 5;
ncols = 5;
z = complex(rand(nrows, ncols), rand(nrows, ncols))

%
% Separate the complex values into real and imaginary components.

z_real = real(z);
z_imag = imag(z);

%
%% Write All Real Components Followed By Imaginary Components
% Write all the real components, z_real, followed by all the imaginary components, z_imag, to a file named complex_adj.bin.

adjacent = [z_real z_imag];

fileID = fopen('complex_adj.bin', 'w');
fwrite(fileID,adjacent,'double');
fclose(fileID);

%
% Read the values from the file using fread.

fileID = fopen('complex_adj.bin');
same_real = fread(fileID, [nrows, ncols], 'double');
same_imag = fread(fileID, [nrows, ncols], 'double');
fclose(fileID);

same_z = complex(same_real, same_imag);

%
%% Interleave Real and Imaginary Components
% An alternative approach is to interleave the real and imaginary components for each value. fwrite writes values in column order, so build an array that combines the real and imaginary parts by alternating rows.
% First, preallocate the interleaved array.

interleaved = zeros(nrows*2, ncols);

%
% Alternate real and imaginary data.

newrow = 1;
for row = 1:nrows
    interleaved(newrow,:) = z_real(row,:);
    interleaved(newrow + 1,:) = z_imag(row,:);
    newrow = newrow + 2;
end

%
% Write the interleaved values to a file named complex_int.bin.

fileID = fopen('complex_int.bin','w');
fwrite(fileID, interleaved, 'double');
fclose(fileID);

%
% Open the file for reading and read the real values from the file. The fourth input to fread tells the function to skip the specified number of bytes after reading each value.

fileID = fopen('complex_int.bin');
same_real = fread(fileID, [nrows, ncols], 'double', 8);

%
% Return to the first imaginary value in the file. Then, read all the imaginary data.

fseek(fileID, 8, 'bof');
same_imag = fread(fileID, [nrows, ncols], 'double', 8);
fclose(fileID);

same_z = complex(same_real, same_imag);

% Copyright 2015 The MathWorks, Inc.