Why Using '%f' as formatspec for a text file containing floating numbers gives no output

3 次查看(过去 30 天)
Hello everyone,
I want to read data fom a text file. Text file contains different rows and column. I used below lines of code to read the data but it returns an empty A:
fileID = fopen('Data.txt', 'r');
formatSpec = '%f';
A = fscanf(fileID, formatSpec);
Secondly, I just want values of t where lat and lon equals:
lat = 32.4876 32.4909
lon = 117.5421 117.5739
Thank you.

采纳的回答

Walter Roberson
Walter Roberson 2021-9-1
target_lats = [32.4876 32.4909];
target_lons = [117.5421 117.5739];
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/726444/Data.txt';
A = readtable(filename, 'readvariablenames', true, 'VariableNamingRule', 'preserve')
A = 5×17 table
col row 1.8 0.5 1.6 1.1 t tt 8.0t 9.7t t0 ssf ph 3.7r r lat lon ___ ___ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ __ _____ ___ ______ ______ 241 169 0.476 0.143 0.236 0.121 313.3 251.7 293.4 271.7 293 302.4 0 0.184 0.5 32.485 117.62 236 170 0.506 0.163 2.399 0.08 300.1 246.7 279.9 262.4 278.7 285.5 0 0.102 0.5 32.488 117.54 237 170 0.52 0.154 2.399 0.084 302.7 248.5 283.6 265.1 282.6 290.3 0 0.112 0.6 32.489 117.56 238 170 0.505 0.149 2.399 0.077 303.2 248.7 284.2 265.4 283.4 291.8 0 0.114 0.8 32.491 117.57 239 170 0.265 0.151 2.399 0.048 302 248.9 284.3 265.6 283.3 291.4 0 0.103 0.1 32.492 117.59
mask = ismembertol(A.lat, target_lats) & ismembertol(A.lon, target_lons);
selected_t = A.t(mask)
selected_t = 2×1
300.1000 303.2000
  1 个评论
Walter Roberson
Walter Roberson 2021-9-1
But to answer your question:
You did not skip any input lines, so your %f was trying to read starting from the very first thing in the file. But the very first thing in the file is the word 'col' which is something that cannot be read with a %f format, so MATLAB stopped reading. fscanf() only continues to read items as long as the format matches, but the word 'col' does not match %f format.

请先登录,再进行评论。

更多回答(1 个)

KSSV
KSSV 2021-9-1
data = importdata('data.txt') ;
data = data.data ;
t = data(:,7) ;
x = data(:,17) ;
y = data(:,16) ;
lat = [32.4876 32.4909] ;
lon = [117.5421 117.5739] ;
t_lon = interp1(x,t,lon) ;
t_lat = interp1(y,t,lat) ;

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by