read value from an external file .txt

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

If you attach your file, you can run your code immediately from the forum interface and it becomes a lot easier to test edits to your code.
The first thing I notice is that you have added <> in your fscanf call and that you don't actually concatenate the char elements. So perhaps this already works:
dataread(i)=fscanf(data,sprintf('Zone %d : %%f',i),[2,inf]);
But I actually expect you would do better if you read the file a string or cellstr and used regular expressions.
2 inf expects at least two values but dataread(i) is a scalar output location.

Sign in to comment.

Answers (1)

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

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.

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Products

Release

R2022b

Asked:

on 10 Feb 2023

Commented:

on 10 Feb 2023

Community Treasure Hunt

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

Start Hunting!