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.
0 个评论
采纳的回答
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')
mask = ismembertol(A.lat, target_lats) & ismembertol(A.lon, target_lons);
selected_t = A.t(mask)
1 个评论
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
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) ;
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!