Convert Array to Text File
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Russell Nasrallah
el 10 de Ag. de 2018
Comentada: Russell Nasrallah
el 13 de Ag. de 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 comentarios
Respuesta aceptada
Stephen23
el 10 de Ag. de 2018
Editada: Stephen23
el 10 de Ag. de 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 comentarios
Stephen23
el 13 de Ag. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!