MATLAB: Reduce trailing zeros of text file

ansysfprintfpointsstudenttext filetrailing zeros

Hello colleagues.
I have the task to create a text file of points to use them on Ansys so my problem is that Matlab creates a column of real numbers but what I need is the first two columns to be integers. I know that I have to use fprintf function but I donĀ“t how to extract the first two columns.
The way the text file is created
1.0000000e+00 1.0000000e+00 -2.6994230e-02 3.0000000e-02 0.0000000e+00
How is needed
1 1 -2.6994230e-02 3.0000000e-02 0.0000000e+00
Thank you

Best Answer

Here's how you use fprintf to export two integer columns followed by three floating point columns:
% Create array with 5 columns and integers in first two columns
x = rand(50, 5) * 100;
x(:, 1:2) = floor(x(:, 1:2))
% Create output text file
fid = fopen('myfile.txt', 'w');
% Write data to file, note:
% - This string exports two integers (%d) followed by three floating point numbers (%f)
% - The numbers are separated by tabs (\t)
% - \n puts a return at the end of each line
fprintf('%d\t%d\t%f\t%f\t%f\n', x');
% Close file
fclose(fid);
This works because in MATLAB fprintf can process arrays. If the array is longer than format string expects, it keeps repeating the format string until the entirety of the array can be printed.
One more note, fprintf linearalizes multi-dimensional arrays. If your data is stored in MATLAB in rows, you'll want to transpose it (as I did in the example) since files are written by rows.