I am trying to do real-time plotting (or close to real-time, as long as it updates every 1 to 2 second) of the temperature vs time. The temperature and time data will be stored in a text file. This text file will be constantly updated by a separate program.
Is it possible to do this using Matlab or C?
I found these codes online, but I have no idea how to use them; do I just create a new Matlab script and put them into the script?
function [t] = livePlot(period, filename)
//% inputs : period : update rate in seconds
//% filename : name of the file to get data from
//%
//% outputs: t : the timer object
//% >> stop(t)
//% ends streaming
//%%
close all;
t = timer('StartDelay', 1, 'Period', period, ...
'ExecutionMode', 'fixedRate');
//%% timer object callback functions
t.StopFcn = {#stopFigure};
t.TimerFcn = {#updateFigure};
//%% initialize timer object user data
d = get(t, 'UserData');
d.data = []; % array for the data to plot
axes('Position', [0 0 1 1], 'Visible', 'off');
d.axes_handle = axes('Position', [.2 .1 .7 .8]);
d.line_handle = plot(NaN,NaN);
d.fid = fopen(filename, 'r');
set(t, 'UserData', d);
start(t);
end
function stopFigure(obj, event)
//% close function handle
d = get(obj, 'UserData');
fclose(d.fid);
end
function updateFigure(obj, event)
d = get(obj, 'UserData');
//% read new data from file
tmp = readFile(obj);
//% append to array in user data
d.data = [d.data transpose(tmp)];
//% update the plot
set(gcf, 'CurrentAxes', d.axes_handle);
set(d.line_handle, 'XData', 1:length(d.data), 'YData', d.data);
//% store the timer object user-data
set(obj, 'UserData', d);
end
function [tmp] = readFile(obj)
//% read binary data. file-ID is in the timer user-data
d = get(obj, 'UserData');
tmp = fread(d.fid);
fprintf('Current file location : %d \n', ftell(d.fid));
//% fprintf('End of file indicator : %d \n', feof(d.fid));
//% reset the end-of-file indicator
fseek(d.fid, -1, 0);
fseek(d.fid, 1, 0);
//% fprintf('End of file indicator : %d \n', feof(d.fid));
set(obj, 'UserData', d);
end
If your text file contain following value for temperature and date.sorry for not in proper format bu consider column 1 for day,2 for time and 3 for temp.
Day Time Temp
1 09:00 16
2 09:00 16.2
Then you can use below sample c code for ploting
f = fopen('yourdata.txt');
c = textscan(f,'%f %s %f','HeaderLines',1);
fclose(f);
d = [c{1}-1 + rem(datenum(c{2},'HH:MM'),1), c{3}];
Related
I'm trying to get a real time plot of data I'm acquiring with a NI USB-6008. I tried doing the same with arduino and got a plot exactly as I wanted (see here https://i.stack.imgur.com/08kzU.jpg), and the x-axis would move in real-time, but I couldn't define the sampling rate. With NI I was able to define the sampling rate I wanted but I can't display the data in a continuous, real-time plot, I can only see 1 sec at a time and I need to be able to have access to all the data acquired since I want to measure a real-time EEG. I'm a new matlab user, so please consider no previous knowledge.
This is the code I've got so far:
clear
close all
dq = daq("ni");
ch1 = addinput(dq, "Dev1", "ai0", "Voltage");
dq.Rate = 1000;
dq.ScansAvailableFcn = #(src,evt) plotDataAvailable(src, evt);
dq.ScansAvailableFcnCount = 100;
start(dq, "Duration", seconds(5))
while dq.Running
pause(0.5);
end
time = 0;
data = 0;
n = ceil(dq.Rate/10);
%Set up Plot
figure(1)
plotGraph = plot(time,data);
title('DAQ data log','FontSize',15);
xlabel ('Elapsed Time (s)','FontSize',10); ylabel('Voltage (V)','FontSize',10);
h = animatedline;
ax = gca;
ax.YGrid = 'on';
ax.XGrid = 'on';
h = animatedline;
function plotDataAvailable(src, ~)
while ishandle(plotGraph) % Loop when Plot is Active will run until plot is closed
data = read(dq,n);
t = datetime('now');
% Add points to animation
addpoints(h,datenum(t),data)
% Update axes
ax.XLim = datenum([t-seconds(15) t]);
datetick('x','keeplimits')
drawnow
end
end
This was my previous arduino code that showed me the plot I needed (with the wrong sampling rate):
clear
clc
%User Defined Properties
a = arduino('com4','uno'); % Define the Arduino Communication port
plotTitle = 'Arduino Data Log'; % Plot title
%Define Function Variables
time = 0;
data = 0;
%Set up Plot
figure(1)
plotGraph = plot(time,data,'-r' );
title(plotTitle,'FontSize',15);
xlabel ('Elapsed Time (s)','FontSize',10); ylabel('Voltage (V)','FontSize',10);
h = animatedline;
ax = gca;
ax.YGrid = 'on';
ax.XGrid = 'on';
ax.YLim = [0 5]; % Sets y-min and y-max
while ishandle(plotGraph) % Loop when Plot is Active will run until plot is closed
startIteration = tic;
voltagem = readVoltage(a,'A0')
t = datetime('now');
% Add points to animation
addpoints(h,datenum(t),voltagem)
% Update axes
ax.XLim = datenum([t-seconds(15) t]);
datetick('x','keeplimits')
drawnow
end
I've tried using this while loop on my NI data but it doesn't work.
I would really appreciate your help.
You've got the order of the operations wrong. What your code is doing at the moment is:
initialize the data acquisition
read the data from the hardware while trying to add data to lines that don't exist
initialize the animated lines.
Furthermore, in your addpoints call you're trying to plot t, which is a scalar, and data, which is an array.
What you should do instead is:
clear
close all
% Set up the plot
figure(1)
title('DAQ data log','FontSize',15);
xlabel ('Elapsed Time (s)','FontSize',10)
ylabel('Voltage (V)','FontSize',10);
h = animatedline;
ax = gca;
ax.YGrid = 'on';
ax.XGrid = 'on';
% Set up the data acquisition
dq = daq("ni");
ch1 = addinput(dq, "Dev1", "ai0", "Voltage");
dq.Rate = 1000;
dq.ScansAvailableFcn = {#plotDataAvailable, h, ax}; % pass also the handle to the line and to the axes
dq.ScansAvailableFcnCount = 100;
% Now you start the data acquisition
start(dq, "Duration", seconds(5))
function plotDataAvailable(src, evt, h, ax)
data = read(dq, n);
% maybe your time array should look something like this?
t = datetime(now) - seconds((length(data)-1:-1:0)./src.Rate);
% Add points to animated line
addpoints(h, datenum(t), data)
% Update axes
% ax.XLim = datenum([t-seconds(15) t]); % this line is useless, why would you have a 15s window when your data acquisition is only 5s long?
datetick('x','keeplimits')
drawnow
end
I can't try this at the moment, so it might not work exactly.
So I think I finally got it, because I got the plot like I wanted, with the x-axis moving with real-time. However I still get an error saying "Unrecognized table variable name 'Dev1_ai0'" event tho I checked that's the name of the row that I want. Anyways, this is what my code looks now.
clear
close all
time = 0;
data = 0;
% Set up the plot
figure(1)
plotGraph = plot(time,data,'-r' );
title('DAQ data log','FontSize',15);
xlabel ('Elapsed Time (s)','FontSize',10)
ylabel('Voltage (V)','FontSize',10);
h = animatedline;
ax = gca;
ax.YGrid = 'on';
ax.XGrid = 'on';
% Set up the data acquisition
dq = daq("ni");
ch1 = addinput(dq, "Dev1", "ai0", "Voltage");
dq.Rate = 1000;
% Start the data acquisition
start(dq, "Duration", seconds(10))
n = ceil(dq.Rate/10);
while ishandle(plotGraph)
data = read(dq, n);
voltage = data.Dev1_ai0;
t = datetime('now');
for i = 1:100
% Add points to animated line
if isvalid(h)
addpoints(h, datenum(t), voltage(i))
end
end
% Update axes
ax.XLim = datenum([t-seconds(15) t]);
datetick('x','keeplimits')
drawnow
end
disp('Plot Closed')
I currently have a code that plots multiple routes on top of a world map within MATLAB. However, I want to be able to tell the code the start and end date-time for the data that I want. I'm not exactly sure where to go about this.
I was able to figure out that doing this would require a GPS file that has Data-Time elements.
clear;
clc;
% Specify folder where the files live
myFolder = 'C:\Users\J87662\Desktop\GPX Data Files';
% Check to make sure folder exists. Warns user if doesn't.
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of all files in the folder with the desired file name pattern.
theFiles = dir(fullfile(myFolder, '*.gpx')); % Using .gpx as the desired file type.
% Number of files in the folder
n = numel(theFiles);
data = cell(1,n);
% Figure with coastlines
figure
load coastlines
geoshow(coastlat, coastlon)
geoshow('landareas.shp', 'FaceColor', [.56 .93 .56]);
% Plotting GPX Data
for k=1:n
% Creates a colormap based on the amount of files we have
cmap = hsv(k);
% Read each file
data{k} = gpxread(fullfile( myFolder, theFiles(k).name ));
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
geoshow(data{1,k}.Latitude, data{1,k}.Longitude);
geoshow(data{1,k}.Latitude, data{1,k}.Longitude, 'Color', cmap(k,:),'LineWidth', 2);
t = data{1,1}.Time;
hold all
end
hold on
Look at the code and comments below. Basically, the start time for a GPS file is stored in the first data point, and the end time is stored in the last data point. Combine all these start and end times in some array, and compare to your time selection criteria.
% init data types
data = cell(n, 1);
dataStartTimes = NaT(n, 1); % init with Not a Time (to store datetime objects)
dataEndTimes = NaT(n, 1);
% load data and get start and end times
for k = 1:n
data{k} = gpxread(fullfile( myFolder, theFiles(k).name));
startTime = data{k}(1).Time; % first time registered
endTime = data{k}(end).Time; % last time registered
dataStartTimes(k) = regexprep(startTime, {'T', '.000Z'}, {' ', ''}); % convert to datetimes
dataEndTimes(k) = regexprep(endTime, {'T', '.000Z'}, {' ', ''}); % convert to datetimes
end
% select gps files based on start and end time
startTime = datetime('21-08-2019 12:00:00', 'InputFormat', 'dd-MM-yyyy HH:mm:ss'); % your selection criteria
endTime = datetime('22-08-2019 12:00:00', 'InputFormat', 'dd-MM-yyyy HH:mm:ss');
selection_indices = find(dataStartTimes >= startTime & dataEndTimes <= endTime);
% select the data
data_selection = data(selection_indices);
% your plotting method:
for k=1:numel(data_selection)
% Creates a colormap based on the amount of files we have
cmap = hsv(numel(data_selection));
geoshow(data{k,1}.Latitude, data{k,1}.Longitude);
geoshow(data{k,1}.Latitude, data{k,1}.Longitude, 'Color', cmap(k,:),'LineWidth', 2);
end
I want to read bits from a file and then to convert them to complex double. Each number is 32 bits (16 Re and 16 Im). Then I want to use qamdemod to get 6 bits per one complex number and to save those bits in new text file.
I did that program but I always gets the same number as output 010011=50
that is the program:
% % Main Algorithm
N=16; %length of one sample
RUNTIME = input('How long you want to run in sec=');
prompt = '0 - for sequentially. 1 - for randomaly =';
n = input(prompt);
x=0;
switch n
case 0
timerID = tic; %# Start a clock and return the timer ID
disp('sequentially');
fid=fopen('rand.bin'); %need to check if file opened
fid_w=fopen('samples.txt','w'); %write to file
while true
%# Perform process
Re=fread(fid,N);
Re=Re'; %transpose to row vector
Im=fread(fid,N);
Im=Im'; %transpose to row vector
if size(Re)~=N
disp('Re is out of range');
break;
end
if size(Im)~=N
disp('Im is out of range');
break;
end
Re_dec=bi2de(Re);
Im_dec=bi2de(Im);
in = (Re_dec/65535) + (Im_dec*(1i)/65535); % unit circle 65535
double(in);
disp("IN:");
disp(in);
out = qamdemod(in,64);
data_out = de2bi(out);
disp(data_out);
fprintf(fid_w,'%f\n',in); %write to sample file
if (feof(fid))
disp('end of file');
break;
end
if(toc(timerID) > RUNTIME) %# Get the elapsed time for the timer
disp('end of time');
break;
end
end
case 1
disp('randomaly')
otherwise
disp('error')
end
fclose('all'); %close all open files
% out = lteSymbolDemodulate(in,'64QAM');
qamdemod was not working correctrly: the right code is:
% % Main Algorithm
RUNTIME = input('How long you want to run in sec=');
prompt = '0 - for sequentially. 1 - for randomaly =';
n = input(prompt);
x=0;
N=16;
fid=fopen('rand.bin'); %need to check if file opened
fid_w=fopen('samples.txt','w'); %write to file
switch n
case 0
disp('sequentially');
sequentially(fid,fid_w,RUNTIME); %call sequentially function
case 1
disp('randomaly');
randomaly(fid,fid_w,RUNTIME); %call randomaly function
otherwise
disp('Error: Wrong select')
end
fclose('all'); %close all open files
fid=fopen('samples.txt'); %need to check if file opened
digest=entropy(fid); %Creating entropy
disp(digest);
fclose('all'); %close all open files
function sequentially(fid,fid_w,RUNTIME)
N=16; %length of one sample
timerID = tic; %# Start a clock and return the timer ID
while true
%# Perform process
Re_bin=fread(fid,N);
if size(Re_bin')~=N
disp('Re is out of range');
break;
end
% disp("Re_bin=");
% disp(Re_bin');
Re=convert_to_number(Re_bin);
Im_bin=fread(fid,N);
if size(Im_bin')~=N
disp('Im is out of range');
break;
end
Im=convert_to_number(Im_bin);
in=complex(Re,Im);
% disp("IN:");
% disp(in);
out = conv_qam64(in);
% disp("OUT:");
% disp(out);
%%%%%%%% if want binary can use bin_out to convert %%%%%%%%%
% bin_out=dec2bin(out);
% disp("OUT BIN:");
% disp(bin_out);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf(fid_w,'%2.0f\n',out); %write to sample file
if (feof(fid))
% disp('end of file');
break;
end
if(toc(timerID) > RUNTIME) %# Get the elapsed time for the timer
% disp('end of time');
break;
end
end
% fclose('all'); %close all open files
I have written a while loop in Matlab that is supposed to send each value in an array from Matlab to arduino at a specified time interval using a tic toc delay in Matlab and then read values and store them in a variable and graph them.
The output of the while-loop slows down with each successive iteration.
I increased the buffersize which helped it a lot, but it still slows down too much. Is there another way to increase the speed to print the values on time. I have included another tic toc and graph to show the execution speed here is the code:
max = 80;
min = 40;
amp = (max-min)/2;
offset = amp + min;
btime = 5;
bpm = 12;
spb = 60/bpm;
sapb = spb/.05;
tosd = sapb*bpm*btime;
time1 = btime*60;
x = linspace(0,time1,tosd)';
x1 = amp*sin(x*(2*pi/20)) + offset;
pause(1);
fprintf(handles.UltraM,(['<P' num2str(offset) '>']))
pause(5);
y = [];
i = 1;
figure(1);
hold on;
title('Pressure Data');
xlabel('Data Number');
ylabel('Analog Voltage (0-1023)');
t1 = [];
figure(2);
hold on;
title('Time to execute task');
xlabel('iteration number');
ylabel('time taken');
while (i<=length(x))
t2 = tic;
t = tic;
fprintf(handles.UltraM,(['<P' num2str(x1(i)) '>']));
%disp((['<P' num2str(x1(i)) '>']));
y(i) = fscanf(handles.UltraM,'%d');
figure(1);
hold on;
plot(i, y(i), 'b*');
drawnow;
hold off;
while toc(t) < 0.05
continue
end
t1(i) = toc(t2);
figure(2);
hold on;
plot(i,t1(i),'b*');
drawnow;
hold off;
i = i + 1;
end
After a bit of back and forth I think I know what you're trying to achieve and what stands in your way.
I have edited your code to make it slightly more fast and readable. Most of the time the operations take just slightly above 0.05 seconds, and at several time points it can take about 5 milliseconds longer than expected. Your millage may vary of course. Since I do not have an arduino, I cannot know if there is a bottle neck there. You should also try profiling your code using the builtin Matlab profiler (it's very useful) to see what exactly slows your code down.
The main thing I found to slow your code is that you used the plot function to add one point at a time to your figure. Each time you call this function, it creates a new graphics object. After a few hundred of those, things get sluggish. Instead you should simply update the already plotted data and redraw it using drawnow.
In short, the solution is this:
1) Initialize you plot with a single point and save the graphics handle for later use:
p1 = plot(0,0,'b*');
2) Then, inside the loop, once your data arrays have been updated, replace the data in your existing plot with the new arrays.
set(p1, 'XData', 1:i, 'YData', y(1:i));
3) Redraw the plots to reflect the latest update.
drawnow;
drawnow will eventually slow down your code also since it has to redraw increasingly large plots at every iteration. To make things work faster, you might want to refresh your plot after a longer interval. For example, the following will refresh every 10 iterations:
if rem(i,10) == 0
drawnow;
end
Full code below. Let me know if you have any more issues.
max = 80;
min = 40;
amp = (max-min)/2;
offset = amp + min;
btime = 5;
bpm = 12;
spb = 60/bpm;
sapb = spb/.05;
tosd = sapb*bpm*btime;
time1 = btime*60;
x = linspace(0,time1,tosd)';
x1 = amp*sin(x*(2*pi/20)) + offset;
pause(1);
%fprintf(handles.UltraM,(['<P' num2str(offset) '>']))
disp(['<P' num2str(offset) '>']); % replacing with disp (I don't have an arduino)
pause(5);
%y = []; % unnecessary here, preallocated before loop
figure(1);
p1 = plot(0,0,'b*'); % plotting one dot to create an object, data will be overwritten
hold on;
title('Pressure Data');
xlabel('Data Number');
ylabel('Analog Voltage (0-1023)');
%t1 = []; % unnecessary here, preallocated before loop
figure(2);
p2 = plot(0,0,'b*'); % plotting one dot to create an object, data will be overwritten
hold on;
title('Time to execute task');
xlabel('iteration number');
ylabel('time taken');
% preallocate t1 and y arrays for faster operation
t1 = zeros(size(x));
y = zeros(size(x));
i = 1; % moved closer to loop beginning for better readability
while i <= length(x) % parentheses unnecessary in Matlab
t2 = tic;
t = tic;
%fprintf(handles.UltraM,(['<P' num2str(x1(i)) '>']));
disp((['<P' num2str(x1(i)) '>'])); % replacing with disp (I don't have an arduino)
%y(i) = fscanf(handles.UltraM,'%d');
y(i) = randn; % replacing with random number (I don't have an arduino)
%figure(1); % unnecessary
%hold on; % unnecessary
%plot(i, y(i), 'b*');
% replacing the above with a slightly faster version
set(p1, 'XData', 1:i, 'YData', y(1:i));
%drawnow; % first one is annecessary
%hold off; % unnecessary
while toc(t) < 0.05
continue
end
t1(i) = toc(t2);
%figure(2); % unnecessary
%hold on; % unnecessary
%plot(i,t1(i),'b*');
% replacing the above with a slightly faster version
set(p2, 'XData', 1:i, 'YData', t1(1:i));
if rem(i,10) == 0 % refreshing every 10 iterations
drawnow;
end
%hold off; % unnecessary
i = i + 1;
end
ANSWER TO PREVIOUS VERSION OF QUESTION
You can vectorize your loop by replacing it entirely with the following two statements:
% vectorizing num-to-string conversion
y4 = cellstr(strcat('<P',num2str(x1), '>'));
% deleting all spaces
y4 = cellfun(#(u) u(~isspace(u)), y4, 'UniformOutput', false)
This small adjustment makes your program run x4 faster on my PC.
Displaying/printing the results could also be done using the cellfun iterator: cellfun(#disp, y4)
Hello I want to calculate realtime FFT plot of my input. With the following code i create a record and calculation. The point is that the calculation is takes to much time to get i nice plot update.
Fs = 44100; % sampling frequency in Hz
T = 1/5; % length of one interval signal in sec
t = 0:1/Fs:T-1/Fs; % time vector
nfft = 2^nextpow2(Fs); % n-point DFT
f = (0:nfft/2)'*Fs/nfft; % Frequency vector
%# prepare plots
figure
hrec(1) = subplot(211);
tplot(1) = plot(t, nan(size(t)), 'Color','b', 'Parent',hrec(1));
xlabel('Time [s]'), ylabel('Amplitude')
hrec(2) = subplot(212);
spec(2) = semilogx(f,nan(size(f)),'Color','b', 'Parent',hrec(2));
xlabel('Frequency [Hz]'), ylabel('Magnitude [dB]'), %XScale('log');
set(hrec, 'Box','on', 'XGrid','on', 'YGrid','on');set(hrec(2), 'XScale','log', 'Xlim',[20 20000]);
% specgram(sig, nfft, Fs);
% prepare audio recording
recObj = audiorecorder(Fs,16,1,0);
% Record
disp('Start Recording...')
for i=1:20
recordblocking(recObj, T);
%# get data and compute FFT
sig = getaudiodata(recObj);
fftMag = 20*log10( abs(fft(sig,nfft)) ); fftMag = fftMag(1:ceil((nfft+1)/2));
% update plots
set(tplot(1),'YData',sig);
set(spec(2), 'YData', fftMag);
title(hrec(1), num2str(i,'Interval = %d'))
drawnow % force MATLAB to flush any queued displays
end
disp('Done.')
So I create a parallel computed calculation:
% Record for 10 intervals of 1sec each
disp('Start speaking...')
for i =1:20
parfor ii=1:2
if ii == 1
recordblocking(recObj, T);
elseif ii == 2
%# get data and compute FFT
sig = getaudiodata(recObj);
fftMag = 20*log10( abs(fft(sig,nfft)) ); fftMag = fftMag(1:ceil((nfft+1)/2));recordblocking(recObj, T);
% update plots
set(tplot(1),'YData',sig);
set(spec(2), 'YData', fftMag);
title(hrec(1), num2str(i,'Interval = %d'))
drawnow %# force MATLAB to flush any queued displays
end
end
end
disp('Done.')
i get now Errors:
Error using audiorecorder/getaudiodata (line 742) Recorder is empty.
Error in parallel_function (line 466)
F(base, limit);
Error in par_plotupdate (line 25) parfor ii=1:2
How do I fix this, because i don't get this error when i don't use the parallel for loop. The last error comes i think from lack of information the first iteration. So i get an a-synchronized loop? or do i make it to difficult…
Thanks
Here is a implementation using asynchron recording. This way recording the audio data runs in the background and the execution of the code is only paused when no data is available. With nearly 100% of the cpu time available to process the data, it came out that processing was possible faster than real-time. This is why I did not use the parallel computing toolbox to further speed-up the process.
Fs = 44100; % sampling frequency in Hz
T = 1/5; % length of one interval signal in sec
t = 0:1/Fs:T-1/Fs; % time vector
nfft = 2^nextpow2(Fs); % n-point DFT
f = (0:nfft/2)'*Fs/nfft; % Frequency vector
%# prepare plots
figure
hrec(1) = subplot(211);
tplot(1) = plot(t, nan(size(t)), 'Color','b', 'Parent',hrec(1));
xlabel('Time [s]'), ylabel('Amplitude')
hrec(2) = subplot(212);
spec(2) = semilogx(f,nan(size(f)),'Color','b', 'Parent',hrec(2));
xlabel('Frequency [Hz]'), ylabel('Magnitude [dB]'), %XScale('log');
set(hrec, 'Box','on', 'XGrid','on', 'YGrid','on');set(hrec(2), 'XScale','log', 'Xlim',[20 20000]);
% specgram(sig, nfft, Fs);
% prepare audio recording
recObj = audiorecorder(Fs,16,1,0);
N=20;
% Record
disp('Start Recording...')
%set up one continuous recording for all N loops. Each loop processes T seconds of data
recObj.record(N*T);
%avoid empty recorder;
pause(.1);
for idx=1:N
%we are continuously recording and this iteration of the loop should process the data from startindex to endindex
startindex=1+(idx-1)*Fs*T;
endindex=(idx)*Fs*T;
audioData=recObj.getaudiodata();
%if not enough data is available, wait.
while size(audioData,1)<endindex
%amount of missing data can be caluclated, wait that time
pause((endindex-size(audioData,1))/Fs);
audioData=recObj.getaudiodata();
end
fprintf('processing index %d to %d\n',startindex,endindex);
%# get data and compute FFT
sig =audioData(startindex:endindex,:);
%If you want to use parallel computing, submit the next line to a worker (http://www.mathworks.com/help/distcomp/createtask.html). Keep in mind that workers can not update your UI, you have to get the results back from the workers.
fftMag = 20*log10( abs(fft(sig,nfft)) ); fftMag = fftMag(1:ceil((nfft+1)/2));
% update plots
set(tplot(1),'YData',sig);
set(spec(2), 'YData', fftMag);
title(hrec(1), num2str(idx,'Interval = %d'))
drawnow % force MATLAB to flush any queued displays
end
disp('Done.')