Read a txt file
Show older comments
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);
Answers (2)
Rafael Hernandez-Walls
on 7 May 2021
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);
Jan
on 7 May 2021
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
Categories
Find more on Standard File Formats in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!