How to add space between heading of txt file?

1 次查看(过去 30 天)
Hey, I have created a txt file and successfully saving data in tabular form But I am having problem in introducing the spaces between the heading of each column. It appears as "h1 h2 h3" but i want space between them so that i may look like "h1______h2_______h3" (without blanks, used to introduce space) Thanks.

回答(1 个)

Prateekshya
Prateekshya 2024-8-22
Hello Khurram,
To format the headers of your text file with spaces between them, you can use MATLAB's fprintf() function with specified field widths. This allows you to align your headers neatly. Here is an example code for the same:
% Step 1: Open the file
fileID = fopen('yourfile.txt', 'w');
% Step 2: Define column headers
header1 = 'h1';
header2 = 'h2';
header3 = 'h3';
% Step 3: Write headers with specified field widths
fprintf(fileID, '%-10s %-10s %-10s\n', header1, header2, header3);
% Example: Write data (replace with your actual data)
data = [1.23, 4.56, 7.89; 9.87, 6.54, 3.21];
[nRows, nCols] = size(data);
% Step 4: Write the data in tabular form
for row = 1:nRows
fprintf(fileID, '%-10.2f %-10.2f %-10.2f\n', data(row, :));
end
% Step 5: Close the file
fclose(fileID);
You can modify the code and the parameters of fprintf() function according to your requirements.
I hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by