fgetl ¨ç¼Æ¥i±N ASCII Àɮתº¤º®e¤¤ªº¬Y¤@¦CŪ¥X¡A¨Ã±N¸Ó¦Cªº ASCII ¤º®e¥HÂন¦r¦ê¶Ç¦^¡C¨Ò¦p¡A¤U¦C«ü¥O¥i±NÀÉ®× mean.m ³v¦C¦L¥X¡G
°õ¦æ¤Wzµ{¦¡«á¡AMATLAB ·|¥ý¦b¥Ø«e¥Ø¿ý§ä´M mean.m¡AY§ä¤£¨ì¡A¦A®Ú¾Ú·j´M¸ô®|¡A§ä¥X mean.m «ü¥Oªº¦ì¸m¡AµM«á¦A±N¨ä¤º®e¤@¦C¤@¦C¦a¦C¥X¡C¡]¬°¸`¬ÙªÅ¶¡¡A¦b¦¹¤£¦C¦L¥Xµ²ªG¡A½ÐŪªÌ¦Û¦æ¸Õ¥Î¦¹½d¨Òµ{¦¡½X¡C¡^Ynª¾¹D¦¹ mean.m ©Ò¦bªº¦ì¸m¡A¥i¿é¤J¡uwhich mean¡v§Y¥iÅã¥Ü¦¹ÀɮשҦbªº¸ô®|¡C
fget ¨ç¼Æ©M fgetl ¨ç¼Æ«Ü¬Û¦ü¡A¨âªÌ§¡¥i¥ÑÀÉ®×Ū¨ú¤@¦C¸ê®Æ¡A¨ä®t§O¦b©ó¡Gfgetl ·|±Ë¥h´«¦æ¦r¤¸¡A¦Ó fgets ¨ç¼Æ«h«O¯d´«¦æ¦r¤¸¡C
§Q¥Î fgetl ¨ç¼Æ¡A§ÚÌ¥i¥H¼ÒÀÀ¦b UNIX ¨t²Î¤Uªº grep «ü¥O¡A¨Ó§ä¥X¥]§t¬Y¤@¯S©w¦r¦êªº¤@¦C¡A¨ä MATLAB ¨ç¼Æ grep.m ¥i¼¶¼g¦p¤U¡G
>> type grep.m
function grep(filename, pattern)
fid = fopen(filename, 'r');
line_number = 0;
while feof(fid) == 0,
line = fgetl(fid);
matched = findstr(line, pattern);
if ~isempty (matched)
fprintf('%d: %s \n', line_number,line);
end
line_number = line_number + 1;
end
fclose(fid);
¨Ò¦p¡A±ý¦C¥X grep.m ¤¤¥]§t 'matched' ¦r¦êªº¨C¤@¦C¡A¥i¿é¤J¦p¤U¡G
>> grep('grep.m', 'matched')
6: matched = findstr(line, pattern);
7: if ~isempty (matched)
Y¤wª¾ ASCII Àɮתº®æ¦¡¡A±ý¶i¦æ§óºë½TªºÅª¨ú¡A¥i¥Î fscanf ¨ç¼Æ¨Ó±qÀɮפ¤Åª¨ú®æ¦¡¤Æ¤§¸ê®Æ¡A¨ä¨Ï¥Î»yªk¦p¤U¡G
matrix = fscanf(fid, format)
¨ä¤¤ fid ¬O±ýŪ¨ú¤§Àɮתº¿ëÃѽX¡]¥Ñ fopen ²£¥Í¡^¡Aformat ¬O®æ¦¡«ü©w¦r¦ê¡]Format Specifier¡^¡A¥Î¥H«ü©wŪ¤J¸ê®Æªº«¬ºA¡A±`¥Îªº®æ¦¡«ü©w¦r¦ê¦³¤U¦C´XºØ¡G
- %s¡G¦r¦ê
- %d¡G10¶i¦ìªº¾ã¼Æ
- %g¡GÂù¿ºë·Ç¡]Double-precision¡^ªº¯BÂI¼Æ¡]Floating-point Numbers¡^
¨ä¥L¦UºØ®æ¦¡«ü©w¦r¦ê¥i¿é¤J help fscanf ¨Ó±o¨ì¸Ô²Óªº½u¤W»¡©ú¡C¨Ò¦p¡A¦³¤@ ASCII ÀÉ®× test.txt ªº¤º®e¦p¤U¡G
>> type test.txt
1 4 9 16 25
36 49 64 81 100
±ý¨Ï¥Î fscanf «ü¥OŪ¨ú¨ä¤º®e¡A¥i¿é¤J¦p¤U¡G
¤W¨Ò¤]Åã¥Ü¤F MATLAB ªº fscanf «ü¥O©M C ªº fscanf «ü¥Oªº³Ì¤j¤£¦P¡GMATLAB ªº fscanf «ü¥O¬O¦V¶q¤Æªº¡]Vectorized¡^¡A¥unŪ¤J¸ê®Æªº«¬ºA¥¿½T¡AMATLAB ªº fscanf «ü¥O·|¤@¦A°õ¦æ¡A¨Ã§â©Ò±oµ²ªG¦s©ñ©ó¤@Ó¦V¶q¨Ã¦^¶Ç¡C
Yn¨î¶Ç¦^¦V¶qªº¤j¤p¡A©Î¬O§Æ±æ¶Ç¦^¤@¯x°}¡A«h¥i¦b fscanf ¥[¤W²Ä¤TÓ¿é¤J¤Þ¼Æ¡A¥H«ü©w¶Ç¦^¦V¶q¡]©Î¯x°}¡^ªº¤j¤p¡C¨Ò¦p¡G±ýŪ¨ú test.txt ªº«e 3 µ§¸ê®Æ¡A¥i¿é¤J¦p¤U¡G
±ý¨Ï fscanf «ü¥O¶Ç¦^¤@Ó 3¡Ñ2 ªº¯x°}¡A¥i¿é¤J¦p¤U¡G
sscanf ¨ç¼Æ©M fscanf ªº¥\¯à«ÜÃþ¦ü¡A°ß¤@¤£¦Pªº¬O¡Asscanf ¨ç¼Æ±q¦r¦ê¡]Strings¡^¤¤Åª¨ú¸ê®Æ¡A¦Ó¤£¬O±qÀɮס]Files¡^¡C¨Ò¦p¡G
MATLABµ{¦¡³]p¡G¤Jªù½g