read value from an external file .txt
Ältere Kommentare anzeigen
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 Kommentare
Rik
am 10 Feb. 2023
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.
Walter Roberson
am 10 Feb. 2023
2 inf expects at least two values but dataread(i) is a scalar output location.
Scacchio
am 10 Feb. 2023
Antworten (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{:}]
dataread=str2double(T)
You don't see much here, because the third is e+22 and the rest is e-22
1 Kommentar
Walter Roberson
am 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
Kategorien
Mehr zu Data Import and Analysis finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!