Read a txt file
1 次查看(过去 30 天)
显示 更早的评论
clc;
clear all;
%%
%%Read DENS.txt
fileID = fopen('DENS.txt','r');
formatSpec = '%d %f';
sizeA = [2 Inf];
A = fscanf(fileID,formatSpec,sizeA);
A = A';
if fileID == -1
disp("ERROR");
end
fclose(fileID);
I need to read a text file like the following with all the precision but with the above code it only read the first 4 decimals
then multiply the second column by 9.11*A(:,2).^(1.326) and save in a new text file, but it only save me a txt file with one column with all the information, first A(:,1) and then A(:,2)
Dens1 = [A(:,1),9.11*A(:,2).^(1.326)];
fileID1=fopen('E1.txt','w');
b=fprintf(fileID1,'%d %.15f\n',Dens1);
fclose(fileID1);
0 个评论
回答(2 个)
Rafael Hernandez-Walls
2021-5-7
try this
Dens1 = [A(:,1),9.11*A(:,2).^(1.326)];
fileID1=fopen('E1.txt','w');
%
[n,~]=size(Dens1);
for k=1:n
b=fprintf(fileID1,'%d %.15f\n',Dens1(k,1),Dens1(k,2));
end
%
fclose(fileID1);
0 个评论
Jan
2021-5-7
Never let a code continue if an error occurs. In larger codes with a lot of output messages will be overseen. Stop with an error instead:
fileID = fopen('DENS.txt','r');
if fileID == -1
error('Cannot open file');
end
formatSpec = '%d %g'; % %g instead of %f
sizeA = [2 Inf];
A = fscanf(fileID, formatSpec, sizeA);
A = A';
fclose(fileID);
Dens1 = [A(:,1), 9.11 * A(:,2) .^ 1.326];
fileID1 = fopen('E1.txt', 'w');
b = fprintf(fileID1, '%d %.15f\n', Dens1.'); % Transpose the data
fclose(fileID1);
Why do you assume, that only 4 decimals are imported? Maybe the display in the command window is limited only. Then try:
format long g
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Low-Level File I/O 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!