Search code examples
matlabtextwhile-loopfgetscell-array

Saving fgets into an array or text file with a time stamp from a while loop


I am using MATLAB to get output from a tracking device for gloves. I basically have:

read = fgets(tracker);
tic
k = 1;

while ischar(read)
   read = fgets(tracker);
   toc

   k = k+1;
end

I want to take 'read', which is a string, and save it with a time stamp from 'toc' from the while loop and be able to save it in a cell array or text file for post processing. This is for a hand tracker in an experiment.

Any thoughts? Thanks


Solution

  • I'd consider using a struct array (non-scalar struct).

    Initialize it:

    tracked = struct('read','','elapsed',[]);
    

    Fill it out:

    tic % then begin reading
    % first iteration
    k = 1;
    tracked(k).read = 'first';
    tracked(k).elapsed = toc;
    % second iteration
    k = 2;
    tracked(k).read = 'second';
    tracked(k).elapsed = toc;
    

    At this point you will have a 1x2 struct array, from which you can easily extract data:

    >> tracked
    tracked = 
    1x2 struct array with fields:
        read
        elapsed
    >> elapsedTimes = [tracked.elapsed]
    elapsedTimes =
       1.0e+03 *
        5.8084    5.8212
    >> readData = {tracked.read}
    readData = 
        'first'    'second'
    

    Of course you could also do a N-by-2 cell array initially, where each row is iteration k and the two columns are the elapsed time and read character data.