Sina - you say that After some time, the data becomes delayed and it has lagged response to my input. What exactly of you mean by this? What is your input? Does the MATLAB code take longer to read from the serial device and so the code is spending more time in the
loop? Or is it that the code is doing more work and is not responding fast enough to your inputs?
The following seems to be doing more than it should or need
last=plot(x(j), SS(j), '.-');
The above is putting the most recent element at the beginning of the array, and then re-plotting all of the data. Only to re-plot the latest element again. Are you plotting time from right to left? And isn't x(1:j-1) equal to get(last,'data')? Are you doing this because the new plot command erases all previous plots, and you are trying to show past history on the figure? If so, then consider using the hold on command. I see that you are using this command already, but I don't think you need both it and the code to re-plot all previous data. You may be able to replace the above with just
As well, consider pre-allocating memory to your x and SS arrays so that they do not grow at each iteration. Since j is at most 10000, then
numIterations = 10000;
x = zeros(numIterations,1);
SS = ones(numIterations,1);
Also, you may want a pause in the first inner while loop
just so that the CPU is able to process other threads.