0

I am running a while loop that is scanning the serial port for data. This while loop is inside a bigger while loop that is continuously acquiring data from an instrument (a spectrometer).

The smaller while loop that scans the port continuously writes to a file until the while condition becomes False. I have noticed that this while loop takes so much time that it interferes with the data acquisition from the spectrometer. I use the commands fread(s) to read from serial port object s and fwrite to write to file. Both these processes seem extremely slow and compromise data acquisition.

Is there a way to speed this up? Is there something I can use that is faster than fread? Should I be writing an array instead of to a file? If so, how do I write to an array during a while loop where I'm unsure of how big the array will be beforehand...

Maheen Siddiqui
  • 539
  • 8
  • 19

1 Answers1

0

A sample code would probably be helpful.

Otherwise, to write to an array of unknown size, I would first preallocate the array say with n where n is big enough, and if needed, you can simply make it bigger.

Something like this. Say you have d entries to write each time.

n = (big number) ;
A = zeros(n, d) ;
i = 1 ;
while(...)
    % do stuff
    A(i,:) = values ; % values = length-d vector
    i = i + 1 ; 
    if i > size(A, 1)
        A = [A ; zeros(n, d)] ;
    end
    i = i + 1 ;
end

This is probably not perfect, but should be good enough for your application I would say.


As a sidenote, note that it is allowed to write something "out of the bounds" of an array. So this is valid

A = zeros(2, 5) ;
A(3,:) = [1 2 3 4 5] ;

But it's very inefficient when done in a loop.

Shawn
  • 593
  • 4
  • 12