Convert Array to Text File
12 ビュー (過去 30 日間)
古いコメントを表示
Hello all, I am trying to determine how to convert a 145x3 array of doubles into a text file of a specific format. I seem to be having trouble with the strategies I've taken so far and was wondering if there any additional suggestions.
I need my output text file to look like this:
Jonswap.txt
< waveheight > < waveperiod > < mainangle >
< waveheight > < waveperiod > < mainangle >
< waveheight > < waveperiod > < mainangle >
I have my variables stored in a 145x3 array as mentioned above. The first column is mainangle the second is waveheight and the third is waveperiod. Each row is a 1 hour time step. I need to write text file that prints each row out as shown above (without the angle brackets), and then moves to the next row.
Any suggestions?
Here is my current attempt:
output = evalc(waveparams_m);
fileID = fopen('jonswap.txt','w');
for i = 1:size(waveparams_m,3)
fprintf(fileID, [output, ' 3.300 20.0000 3600 1' ]);
fprintf(fileID, '\n')
end
fclose(fileID);
type jonswap.txt
The additional values at the end ('3.300 20.0000 3600 1') are standard for each time step and do not change.
Thanks!
0 件のコメント
採用された回答
Stephen23
2018 年 8 月 10 日
編集済み: Stephen23
2018 年 8 月 10 日
Your approach is very inefficient: you don't need a loop, you certainly don't need evalc. It is much more efficient to use the fprintf format string properly to convert the numeric values:
[fid,msg] = fopen('jonswap.txt','wt');
assert(fid>=3,msg)
fprintf(fid, '%g %g %g 3.300 20.0000 3600 1\n', waveparams_m.');
fclose(fid);
Note that I used the %g format specifier: you can read the fprintf help to learn about the format string, and how to modify the number format, digits used, field width, etc.
3 件のコメント
Stephen23
2018 年 8 月 13 日
"but the parts I was trying to print from the array were printed as weird square characters"
This means the format string was not defined correctly for the numeric values: possibly you were using %c or %s with the numeric values, which could convert the numeric values into strange characters.
If you want help with the correct numeric formats then please upload your sample numeric array by clicking the paperclip button, AND specify how you want the numbers to be displayed:
- notation: fixed point, integer, exponent,...
- precision or number of decimal digits.
- trailing zeros.
- leading zeros
- field width, etc.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!