Convert Array to Text File
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Russell Nasrallah
le 10 Août 2018
Commenté : Russell Nasrallah
le 13 Août 2018
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 commentaires
Réponse acceptée
Stephen23
le 10 Août 2018
Modifié(e) : Stephen23
le 10 Août 2018
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 commentaires
Stephen23
le 13 Août 2018
"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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!