Reduce trailing zeros of text file
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Josh
2019-5-17
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!