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!