How to include complex numbers in fprintf function?

M
McCormack · Dec 5, 2023 · 2.1K views
Question
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 PhD Expert
Answered Aug 24, 2026
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

 

100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!