How to include complex numbers in fprintf function?

Illustration
McCormack - 2023-12-05T15:09:32+00:00
Question: How to include complex numbers in fprintf function?

lambda = [1.064e-6]; R = [30]; w=[0.001]; q = (1./R- i* lambda./pi./w.^2).^(-1); a=1; p=1; m=1; probe_r=linspace(0,0.003,100); probe_theta=linspace(0,0.003,100); rseed=[0*max(w):max(w)/30:3*max(w)]; thetaseed=[0:360]*pi/180; [r,theta]=meshgrid(rseed,thetaseed); E=LaguerreGaussianE([p,m,q,lambda,a],r,theta); V=interp2(r,theta,E,probe_r,probe_theta); column_names = {'r', 'theta', 'V'}; fid = fopen('fidtext.txt','wt'); fprintf(fid, '%s ', column_names{:}); fprintf(fid, '\n'); block_of_data = [probe_r, probe_theta, V]; fmt = repmat('%15g ', 1, 3); fmt(end:end+1) = '\n'; fprintf(fid, fmt, block_of_data.'); fclose(fid); With the current code I have I get a .txt file of only the real numbers from my function V along with the values of probe_r and probe_theta. How do I alter this to produce both the real and complex numbers as a 3 column .txt file of r, theta and V as I am unable to see a formatSpec to include complex numbers.  

Expert Answer

Profile picture of Neeta Dsouza Neeta Dsouza answered . 2025-11-20

you have to write the real and complex parts separately.
 
Example
 
x = sqrt(-2);
fprintf(fid, '%f%+fj\n', real(x), imag(x))

0.000000+1.414214j

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!