title: Matlab reading from serial port at specific sampling rate
body: <p>I am trying to read values from two sensors (on my arduino) that are being sent to the serial port, with the matlab code below. However, it errors saying <code>??? Attempted to access sensor1(1); index out of bounds because numel(sensor1)=0</code> and if the error does not occur the results are not accurate. I know this because I simply sent 1 and 2 as the sensor values to the com port and the resulting two arrays contained some zeros too (when one should be all 1's and the other all 2's). Thanks any help will be greatly appreciated.</p>
  
  <p>Here is my matlab code: </p>
  
  <pre><code>close all;
  clc;
  
  fs = 1000;  % sampling frequency (samplings per second)
  mt = 20;  % time for measurements
  
  ind = 1;
  nind = 1;
  
  %Open serial port
  delete(instrfind({'Port'},{'/dev/tty.usbmodem641'}));
  serial_port=serial('/dev/tty.usbmodem641');
  serial_port.BaudRate=115200;
  warning('off','MATLAB:serial:fscanf:unsuccessfulRead');
  
  %Open serial port
  fopen(serial_port); 
  
  pause(2);
  
  %Declare sample count
  sample_count=1;
  
  
  tic;
  while toc &lt; mt
  
      time(ind) = toc;
  
      sensor1=fscanf(serial_port,'%d')';
      sensor2=fscanf(serial_port,'%d')';
  
      channel1(ind) = (sensor1(1));
      channel2(ind) = (sensor2(1));
  
      % wait for appropriate time for next measurement
      while( nind == ind )
          nind = floor(toc*fs) + 1;
      end
      ind = nind;
  
  
  end 
  
  %close connection
   fclose(serial_port); 
   delete(serial_port);
  </code></pre>
  
  <p>this is my sending arduino code:</p>
  
  <pre><code>int sensor1=0;
  int sensor2= 0;
  
  void setup(){
  
    Serial.begin(115200);
  
  }
  
  void loop(){
  
    sensor1= 1;
    sensor2= 2;
  
    Serial.println(sensor1);
    Serial.println(sensor2);
  
  
  }
  </code></pre>