How do I read in mixed ASCII and numeric data?
14 ビュー (過去 30 日間)
古いコメントを表示
MathWorks Support Team
2009 年 11 月 17 日
編集済み: MathWorks Support Team
2016 年 10 月 18 日
I have a file where strings and data are mixed in the following format:
FP1 2.34 5.66 6.77 7.88
Cp6 2.44 5.55 7.77 7.88
RTP12 5.55 3.33 6.66 5.55
I would like to open this file and get the ASCII strings and numeric data into MATLAB.
採用された回答
MathWorks Support Team
2016 年 10 月 18 日
Here are two quick example MATLAB code fragments that will read in data that is in the format:
string # # # #
This is the only format that this file can read. If your data is in a different format, you will need to adjust the FSCANF statement accordingly.
NOTE: This is only an example and is provided, as is, without additional support. For more information on any of the functions used in this MATLAB file, type "help {function-name}".
% Find out number of rows in file
r=0;
x=0;
% Open Data File
fid = fopen('data.dat','rt');
% Loop through data file until we get a -1 indicating EOF
while(x~=(-1))
x=fgetl(fid);
r=r+1;
end
r = r-1;
disp(['Number of rows = ' num2str(r)])
frewind(fid);
for i = 1:r
name = fscanf(fid,'%s',1); % Filter out string at beginning of line
num = fscanf(fid,'%f %f %f %f\n')'; % Read in numbers
if(i==1)
names = name; % Add 1st text string
result = num; % Add 1st row
else
names = str2mat(names,name); % Add next string
result = [result;num]; % Add additional rows
end
end
fclose(fid);
disp(' ')
disp('Data read in successfully:')
disp(result)
disp(' ')
disp('Strings read in successfully:')
disp(names)
disp(' ')
The following code will read the data and ignore the characters,
fid = fopen('data.dat','r');
b = fscanf(fid,'%*s %g %g %g %g');
b=[reshape(b,4,3)]'
fclose(fid);
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Workspace Variables and MAT Files についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!