read data line by line from a .dat file after pressing a certain keyboard key

조회 수: 2 (최근 30일)
Mohamed Ali
Mohamed Ali 2017년 10월 21일
댓글: Walter Roberson 2017년 10월 21일
Hello, i'm new to Matlab and need to create a function which read data line by line from a .dat file after pressing a certain keyboard key and then save them to multiple outputs, the same idea as scanf in C or textread in Matlab ([A,B,C,...] = textread(filename,format))
my data looks like:
  • 7 1099 236 260 236 260 0
  • 2 1078 236 300 236 300 0
  • 3 1829 236 100 236 100 0
  • 4 1367 206 500 206 500 0
  • 1 1123 246 170 246 170 0

답변 (1개)

Gareth Thomas
Gareth Thomas 2017년 10월 21일
  댓글 수: 4
Mohamed Ali
Mohamed Ali 2017년 10월 21일
If there's an alternative than eval to pass each line value to a function to work on it later!
Walter Roberson
Walter Roberson 2017년 10월 21일
textlines = regexp( fileread(filename), '\r?\n', 'split');
if isempty(textlines{end}); textlines{end} = []; end %file might or might not have ended in newline
YourResults = cellfun(@(onetextline) YourTextFunction(onetextline), lines, 'Uniform', 0);
Or, better:
num_cols = 7;
fmt = repmat('%f', 1, num_cols);
fid = fopen(filename, 'r');
YourInputCell = textscan(fid, fmt, 'CollectOutput', 1);
fclose(fid);
YourInputNumeric = YourInputCell{1};
YourResults = arrayfun(@(RowIdx) YourNumericFunction( YourInputNumeric(RowIdx,:) ), (1:size(YourInputNumeric,1)).', 'Uniform', 0 );

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Desktop에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by