フィルターのクリア

Reduce trailing zeros of text file

1 回表示 (過去 30 日間)
Osvaldo Benítez
Osvaldo Benítez 2019 年 5 月 17 日
コメント済み: Osvaldo Benítez 2019 年 5 月 17 日
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

採用された回答

Josh
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.
  1 件のコメント
Osvaldo Benítez
Osvaldo Benítez 2019 年 5 月 17 日
Perfect! TVM friend!
Only you were missing de file ID after the first parentheses of fprintf but everything else works just fine.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by