Importing data from a file in a specific way

조회 수: 2 (최근 30일)
g
g 2019년 3월 17일
답변: Walter Roberson 2019년 3월 17일
I have a file with 3 columns of data.
Here is just a sample of what the data looks like (there are many more rows):
265.54555556 1.09773e-46 1.04772e-23
265.54611111 3.60808e-47 6.00673e-24
265.54666667 1.25291e-46 1.11934e-23
I want to read this into Matlab (with the numbers formatted with the same precision) and be able to work with specific columns. This is what I have. I'm not sure what is going wrong or if I even am reading in the numbers properly for their values.
fileID = fopen(file,'r');
formatSpec='%f %12.5e %12.5e';
sizeA = [Inf 3];
A = fscan(fileID,formatSpec,sizeA);
disp(A);
Additionally, once I have this working, how would I select a specific column?
Thanks!
  댓글 수: 3
g
g 2019년 3월 17일
편집: g 2019년 3월 17일
There is no specific reason, I suppose. I was just trying to avoid those very small numbers being interpreted as 0.0000 for instance- I want them to keep their values on the order of 10^-46, etc. I don't believe I'm working with fixed width.
Walter Roberson
Walter Roberson 2019년 3월 17일
%f knows about exponential format.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2019년 3월 17일
fileID = fopen(file, 'r');
formatSPec = '%f %f %f';
sizeA = [3 Inf]; %notice not [Inf 3]
A = fscanf(fileID, formatSpec, sizeA) .'; %notice transpose
fclose(fileID);
Or
A = cell2mat( textscan( fileread(file), '%f %f %f') );
And afterwards, A(:,2) would be the second column.

추가 답변 (1개)

Guillaume
Guillaume 2019년 3월 17일
The numbers in your text file have less precision than matlab uses. So, the simplest thing is to load them with csvread (or dlmread):
data = csvread(file);
Note that the precision with which matlab displays the numbers is completely different to the precision at which they're stored. Use format to change the display precision.

카테고리

Help CenterFile Exchange에서 Descriptive Statistics에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by