1
votes

I need to simulate a sensor sending data in order to test my algorithm. How can I do this in MATLAB? For example, say I create a noisy sine wave like this:

t = [0:1:1000];
vn = .2;
f = .5;
fs = 50;
x = 4*sin(2*pi*f/fs*t) + vn*rand(size(t));

x is simulation data only, where f is the frequency of the signal and fs is the sampling frequency. I would like to get one element of x every .02 seconds, or 50 Hz, into a function I have defined. So, when my function starts I would get x(1), then at 0.02 seconds later I would get x(2) and so on...

I really appreciate any help you can provide.

2

2 Answers

1
votes

This can be done using a timer object:

x = 11:20; % some test data
myFunction = @(i) disp(x(i)); % test function that just displays x(i)
i = 1;

% configure the timer
t = timer;
t.TimerFcn = 'myFunction(i); i = i + 1;'
t.StopFcn = @(timerObj, ~) delete(timerObj) % required according to manual
t.Period = 0.5; %change this later to 0.02
t.ExecutionMode = 'fixedRate';
t.TasksToExecute = length(x);

start(t) % start the timer
0
votes

If you want to be really accurate you can pause your execution for the needed time. For example:

for i=1:1:length(x)
 .....
 pause(0.02)
end

This will work assuming the time taken to process your time is dismissful. If it is not you may want to consider tic-toc to get t- the time taken for processing and then pause for 0.02-t.