Load a text file containing both numbers and letters

帅比萌擦擦* 提交于 2019-12-01 23:45:44

Call fopen, fscanf, and fclose. The format string must be different for lines containing only letters (like '%s\t%s\t%s'), and for those which contain only numbers (like '%g\t%g\t%g'). You can read lines of identical structure with a single fprintf call.

Example file (data.txt):

A        B        C
D        E        F
1        2        3
4        5        6
7        8        9
10       11       12

Suppose that we know in advance that the file contains 3 columns, and 2 lines with characters at the beginning:

fid = fopen('data.txt', 'r');
[x, nx] = fscanf(fid, '%s\t%s\t%s', [3, 2]);
[y, ny] = fscanf(fid, '%g\t%g\t%g', [3, Inf]);
fclose(fid);

The lines with the characters will be in x', and the lines with numbers will be contained by y'.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!