read value from an external file .txt

7 views (last 30 days)
Scacchio
Scacchio on 10 Feb 2023
Commented: Walter Roberson on 10 Feb 2023
I have an external file to read in Matlab with *.txt format and I need to save the value of each zone in an array dataread to plot.
For example the file read.txt have this data:
Results:
Zone 2 : 4,565e-0022
Zone 3 : 4,565e-0022
Zone 4 : 4.565e-0022
Zone 5 : 4.565e-0022
total: 5464.002e-2
I try to use the script but it does not work. How can i solve it?
data=fopen('read.txt','r')
tline=fgets(data); % to read the next line
for i=2:(end(data)-1)
dataread=fscanf(data,'<Zone 'num2str(i) ' :> %f',[2,inf]);
end
also, for some decimal values commas are used for others points, how can I standardize?
  3 Comments
Walter Roberson
Walter Roberson on 10 Feb 2023
2 inf expects at least two values but dataread(i) is a scalar output location.

Sign in to comment.

Answers (1)

Rik
Rik on 10 Feb 2023
You can do it with fscanf, but it you get a lot more flexibility if you use a regular expression instead. If you want to use this code on an older release: my readfile function will read a text file to a cellstr, just like the first line below does.
data=cellstr(readlines('read.txt'));
T=regexp(data,'Zone\s*\d\s*:\s*(\d*[,\.]?\d*[eE]?[-+]?\d*)','tokens');
T=[T{:}];T=[T{:}]
T = 1×4 cell array
{'4.565e-0022'} {'3.555e-0022'} {'1.132e+0022'} {'4.565e-0022'}
dataread=str2double(T)
dataread = 1×4
1.0e+22 * 0.0000 0.0000 1.1320 0.0000
You don't see much here, because the third is e+22 and the rest is e-22
  1 Comment
Walter Roberson
Walter Roberson on 10 Feb 2023
Using 4-digit numbers for exponents is pretty strange. It does have meaning if you are using Intel 80 bit floating point numbers, but those are designed to be for internal use only and are not intended to make it to end-users

Sign in to comment.

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!