How to model time in matlab? - matlab

I am implementing a scheme in Matlab in which a particular node A waits for time period t(defined by the distance between the farthest node within A's range and the propagation speed of the signal) for acknowledgements from a set of nodes after sending a message. If it does not receive any acknowledgement with in time period t, it takes some action.
I have no idea how to implement time in Matlab. Is it possible or I'll have to find some way around?

You can use MATLAB's powerful datetime:
For example: you want to check if the signal is received within the acceptable delay (in this example, 40 milliseconds):
% t = datetime(Y,M,D,H,MI,S,MS);
send = datetime(2016,08,31,06,01,00,00);
receive=datetime(2016,08,31,06,01,00,100);
acceptableDelay=datenum(40/(24*60*60*1000));
if ((receive-send)<acceptableDelay)
disp('Well received!')
else
disp('Late!')
end

Related

MATLAB SIMULINK implementing a discrete increment/decrement counter?

I have a signal which will be either 1,0 or -1 for a discrete time interval (say 10s) then change depending on other parameters. I want a counter to keep a running count of an Initial Value modified by the input signal.
example:
t0->t1, input=1, output=initialvalue+1
t1->t2, input=0, output=initialvalue+1
t2->t3, input=1, output=(initialvalue+1)+1
t3->t4, input=-1, output=((initialvalue+1)+1)-1
etc. Ideally I would want this to work for input being any integer but I'll take what I can get...
There's a counter block but it only counts up or down, not both. I tried using edge detection but I'm not sure how to implement the discrete counter on which it operates. Any help highly appreciated.

Is it possible to stop a Simulink simulation when a certain condition is met?

Assume that you have a Simulink simulation where a certain signal is first positive and after some time t in a given interval, it becomes negative. Your goal is to find the zero-crossing.
A first approach would be to plot the signal over the given interval, save it and calculate the zero-crossing.
When repeating this simulation numerous times for varying parameters, it would be beneficial to be able to stop the simulation after the signal has become negative. Then there is already enough information for the calculation of the zero-crossing in Matlab. How could you do that?
Yes, use the Stop Simulation block with the appropriate logical input to the block:
You can use an if / else block to control the flow in the Simulink model. In the if / else block, you can choose the condition if u > 0, continue as normal if it's true, and use the else-option to bypass the rest of the flow you would otherwise run. For instance jump directly to the scope.
Another ways:
You can use Hit Crossing Block in Simulink to find time at the moment of hitting zero.
Another way - use any Trigger or Resettable system. It detects the zero crossing too. For example: this question at SO.
Of course you can also use User Defined function to detect zero crossing by your hand and do whatever you want with the signal at the same time.
About making a lot of simulations and then stops:
you can use Check Upper Static Bound for automatically stops simulation at the moment when zero will be crossed in nth time. For example:
I set upper bound = 10 for this block and this stops at 10th crossing.
There are a lot of ways to save function values in this points or just array of times but this is an another question :)

Variable transport delay using time after threshold has been reached in Simulink

In Simulink how can I delay the transport block to the exact time of when a certain threshold has been reached?
Basically I have an S-function which switches to an alternate input source, a sine wave, after a certain value has been reached. As soon as the switch occurs I want to start the sine wave. For that I need to delay the wave generation until the switch occurs.
How can I send that time to the Variable transport delay block?
Maybe you can try this way:
you need Variable Integer Delay for example. It changes delay to what you need. Calculate needed value of delay you can in User Defined Function, route to it your threshold value and current time and all other values you need.
Hope i understood your question correctly!

Simulation: send packets according to exponential distribution

I am trying to build a network simulation (aloha like) where n nodes decide at any instant whether they have to send or not according to an exponential distribution (exponentially distributed arrival times).
What I have done so far is: I set a master clock in a for loop which ticks and any node will start sending at this instant (tick) only if a sample I draw from a uniform [0,1] for this instant is greater than 0.99999; i.e. at any time instant a node has 0.00001 probability of sending (very close to zero as the exponential distribution requires).
Can these arrival times be considered exponentially distributed at each node and if yes with what parameter?
What you're doing is called a time-step simulation, and can be terribly inefficient. Each tick in your master clock for loop represents a delta-t increment in time, and in each tick you have a laundry list of "did this happen?" possible updates. The larger the time ticks are, the lower the resolution of your model will be. Small time ticks will give better resolution, but really bog down the execution.
To answer your direct questions, you're actually generating a geometric distribution. That will provide a discrete time approximation to the exponential distribution. The expected value of a geometric (in terms of number of ticks) is 1/p, while the expected value of an exponential with rate lambda is 1/lambda, so effectively p corresponds to the exponential's rate per whatever unit of time a tick corresponds to. For instance, with your stated value p = 0.00001, if a tick is a millisecond then you're approximating an exponential with a rate of 1 occurrence per 100 seconds, or a mean of 100 seconds between occurrences.
You'd probably do much better to adopt a discrete-event modeling viewpoint. If the time between network sends follows the exponential distribution, once a send event occurs you can schedule when the next one will occur. You maintain a priority queue of pending events, and after handling the logic of the current event you poll the priority queue to see what happens next. Pull the event notice off the queue, update the simulation clock to the time of that event, and dispatch control to a method/function corresponding to the state update logic of that event. Since nothing happens between events, you can skip over large swatches of time. That makes the discrete-event paradigm much more efficient than the time step approach unless the model state needs updating in pretty much every time step. If you want more information about how to implement such models, check out this tutorial paper.

PWM/clock signal generation from a USB-1024HLS DAQ board

Is there an API function call for this board that would allow me to generate a clock signal on an output at 500 kHz while running some other code on the board? Thanks in advance for the advices.
According to the Supported Hardware documentation, version 2.8 or greater of the Data Acquisition Toolbox is needed to support a Measurement Computing USB-1024HLS device. Assuming you have version 2.8 or newer, the following should come close to a solution for you...
The first step would be to get the hardware ID for the device. The function DAQHWINFO should help with this:
deviceInfo = daqhwinfo('mcc');
The hardware ID gotten from the structure deviceInfo can then be used to create a Digital I/O Object (DIO) using the DIGITALIO function:
dio = digitalio('mcc',hardwareID);
Next, you have to add two output lines (for a clock signal and a pulse-width modulation (PWM) signal) using ADDLINE:
addline(dio,0:1,'out');
Then, you have to set a few DIO properties.
set(dio,'TimerPeriod',0.000002); % i.e. 500 kHz
set(dio,'TimerFcn',#update_outputs);
The function update_outputs is called once every timer period and should set the output pins to the appropriate values. The clock signal is simply going to switch back and forth between 0 and 1 every timer period. The PWM signal will likely alternate between 0 and 1 as well, but it will not change every timer period, remaining in each state for a set amount of time based upon the sort of pulse-width modulation you want. Here's what your update_outputs function may end up looking like:
function update_outputs(obj,event)
currentValues = getvalue(obj);
clockValue = ~currentValues(1);
pwmValue = pwm_compute();
putvalue(obj,[clockValue pwmValue]);
end
Note that this uses PUTVALUE and GETVALUE to set/get the values of the output pins. You will have to write the function pwm_compute such that it computes a new PWM value for each time period. Since pwm_compute will likely have to know how many values have been output already (i.e. how many times it has already been called), you can track that using a persistent variable:
function newValue = pwm_compute
persistent nValues;
if isempty(nValues)
nValues = 0;
else
nValues = nValues+1;
end
...
% Compute the new value for the (nValues+1) time period
...
end
This is just one possible solution. You could potentially precompute the PWM signal and pull the value for each timer period from a vector or data file, or you could potentially use the event data structure passed to update_outputs to get the time of the timer event (relative to the DIO timer start, I believe).
Finally, you have to start the DIO:
start(dio);
...and, once you're finished using it, delete it and clear it from memory:
delete(dio);
clear dio;
One potential stumbling block...
Generating a 500 kHz signal could be difficult. It's such a high frequency that you may run into problems, specifically with the 'TimerFcn', which is called once every timer period. If the 'TimerFcn' takes longer than 0.000002 seconds to run, some timer events may not be processed, leading to an output that is actually of a lower frequency. I have a feeling you may have to use a lower signal frequency for things to work properly, but I could be wrong. =)
I found Example: Generating Timer Events in the Data Acquisition Toolbox documentation.
dio = digitalio('nidaq','Dev1');
addline(dio,0:7,'in');
set(dio,'TimerFcn',#daqcallback)
set(dio,'TimerPeriod',5.0)
start(dio)
pause(11)
delete(dio)
clear dio