Generate on/off signals of random duration SIMULINK - events

For my SIMULINK model I need to generate a signal that takes the values 1 or 0. To generate it I need to draw a number from a an exponential distribution and use this number as the time the signal stays in 0. Once this time has passed, I have to draw a new number from the exponential distribution and use this number as the time the signal stays in 1, and the repeat the process until the end of the simulation. As a SIMULINK newbie I'm quite puzzled by this problem and would appreciate any suggestions on how to solve it.

You've got a couple of choices.
In MATLAB, you can generate all samples in advance (i.e. before running the simulation) and use them to create a suitable signal, then use that as an input into the model (using the From Workspace block).
Or, if you need to do the sampling at each time step, then you have to write an S-Function, using the random number in the mdlGetTimeOfNextVarHit method. There is an example of doing something very similar on the Goddard Consulting web site called Square Wave with Jitter.

Related

How to Change sample times from continuous or constant to discrete in simulink

I am experiencing the following error in my simulink model, Simulink version 7.6
"All sample times for 'onlineclassifier/Enabled Subsystem/bufferSampW' must be discrete. No continuous or constant sample times are allowed"
I am loading a 50X231 matrix that has in the first row the time samples (so in reality is 49X231), with 231 sample times. I am trying to read one column of the matrix at a time after an external trigger and use it for a matrix multiplication. The problem is that this matrix is loaded in continuous time and I have not been able to convert it into a discrete time matrix.
How can I do this?
I only need to use the matrix for a period of time given by the external event. This is a fixed matrix for all the simulink session.
any input is highly appreciated.
Thanks.
Use Rate transiition block before descrete block and change the sample time of Rate transition block other than continous and constant i.e. other than "-1 /inf" (e.g. try 0.1)

Generating Random Number AVR without seed

I writing an application in AVR Studio 4 which generates random numbers and outputs them on a seven segment display. At the moment i am using a seed, the seed value then gets randomized and the value output. This method obviously produces the same random number sequence (and displays the same sequence) every time the program is run. Is there an alternate method i can use which does not use a seed and as such does not start the program with the same number each time, allowing for different random numbers.
Thanks
Each time the microcontroller starts up it is seeing exactly the same internal state as any other time it starts up. This means its output will always be the same regardless of any algorithm you might use.
The only way to get it to produce different behaviour is to somehow modify its state at startup by introducing some external information or by storing state between startups. Some ideas for how to do the first option might be to measure the duration of a user key press (if your system has buttons) or sensing a temperature or other external input and using this to seed the algorithm. However the simplest option is probably to just store a counter in EEPROM that is incremented after each startup and use this to generate the seed.

In matlab, speed up cross correlation

I have a long time series with some repeating and similar looking signals in it (not entirely periodical). The length of the time series is about 60000 samples. To identify the signals, I take out one of them, having a length of around 1000 samples and move it along my timeseries data sample by sample, and compute cross-correlation coefficient (in Matlab: corrcoef). If this value is above some threshold, then there is a match.
But this is excruciatingly slow (using 'for loop' to move the window).
Is there a way to speed this up, or maybe there is already some mechanism in Matlab for this ?
Many thanks
Edited: added information, regarding using 'xcorr' instead:
If I use 'xcorr', or at least the way I have used it, I get the wrong picture. Looking at the data (first plot), there are two types of repeating signals. One marked by red rectangles, whereas the other and having much larger amplitudes (this is coherent noise) is marked by a black rectangle. I am interested in the first type. Second plot shows the signal I am looking for, blown up.
If I use 'xcorr', I get the third plot. As you see, 'xcorr' gives me the wrong signal (there is in fact high cross correlation between my signal and coherent noise).
But using "'corrcoef' and moving the window, I get the last plot which is the correct one.
There maybe a problem of normalization when using 'xcorr', but I don't know.
I can think of two ways to speed things up.
1) make your template 1024 elements long. Suddenly, correlation can be done using FFT, which is significantly faster than DFT or element-by-element multiplication for every position.
2) Ask yourself what it is about your template shape that you really care about. Do you really need the very high frequencies, or are you really after lower frequencies? If you could re-sample your template and signal so it no longer contains any frequencies you don't care about, it will make the processing very significantly faster. Steps to take would include
determine the highest frequency you care about
filter your data so higher frequencies are blocked
resample the resulting data at a lower sampling frequency
Now combine that with a template whose size is a power of 2
You might find this link interesting reading.
Let us know if any of the above helps!
Your problem seems like a textbook example of cross-correlation. Therefore, there's no good reason using any solution other than xcorr. A few technical comments:
xcorr assumes that the mean was removed from the two cross-correlated signals. Furthermore, by default it does not scale the signals' standard deviations. Both of these issues can be solved by z-scoring your two signals: c=xcorr(zscore(longSig,1),zscore(shortSig,1)); c=c/n; where n is the length of the shorter signal should produce results equivalent with your sliding window method.
xcorr's output is ordered according to lags, which can obtained as in a second output argument ([c,lags]=xcorr(..). Always plot xcorr results by plot(lags,c). I recommend trying a synthetic signal to verify that you understand how to interpret this chart.
xcorr's implementation already uses Discere Fourier Transform, so unless you have unusual conditions it will be a waste of time to code a frequency-domain cross-correlation again.
Finally, a comment about terminology: Correlating corresponding time points between two signals is plain correlation. That's what corrcoef does (it name stands for correlation coefficient, no 'cross-correlation' there). Cross-correlation is the result of shifting one of the signals and calculating the correlation coefficient for each lag.

About random number sequence generation

I am new to randomized algorithms, and learning it myself by reading books. I am reading a book Data structures and Algorithm Analysis by Mark Allen Wessis
.
Suppose we only need to flip a coin; thus, we must generate a 0 or 1
randomly. One way to do this is to examine the system clock. The clock
might record time as an integer that counts the number of seconds
since January 1, 1970 (atleast on Unix System). We could then use the
lowest bit. The problem is that this does not work well if a sequence
of random numbers is needed. One second is a long time, and the clock
might not change at all while the program is running. Even if the time
were recorded in units of microseconds, if the program were running by
itself the sequence of numbers that would be generated would be far
from random, since the time between calls to the generator would be
essentially identical on every program invocation. We see, then, that
what is really needed is a sequence of random numbers. These numbers
should appear independent. If a coin is flipped and heads appears,
the next coin flip should still be equally likely to come up heads or
tails.
Following are question on above text snippet.
In above text snippet " for count number of seconds we could use lowest bit", author is mentioning that this does not work as one second is a long time,
and clock might not change at all", my question is that why one second is long time and clock will change every second, and in what context author is mentioning
that clock does not change? Request to help to understand with simple example.
How author is mentioning that even for microseconds we don't get sequence of random numbers?
Thanks!
Programs using random (or in this case pseudo-random) numbers usually need plenty of them in a short time. That's one reason why simply using the clock doesn't really work, because The system clock doesn't update as fast as your code is requesting new numbers, therefore qui're quite likely to get the same results over and over again until the clock changes. It's probably more noticeable on Unix systems where the usual method of getting the time only gives you second accuracy. And not even microseconds really help as computers are way faster than that by now.
The second problem you want to avoid is linear dependency of pseudo-random values. Imagine you want to place a number of dots in a square, randomly. You'll pick an x and a y coordinate. If your pseudo-random values are a simple linear sequence (like what you'd obtain naïvely from a clock) you'd get a diagonal line with many points clumped together in the same place. That doesn't really work.
One of the simplest types of pseudo-random number generators, the Linear Congruental Generator has a similar problem, even though it's not so readily apparent at first sight. Due to the very simple formula
you'll still get quite predictable results, albeit only if you pick points in 3D space, as all numbers lies on a number of distinct planes (a problem all pseudo-random generators exhibit at a certain dimension):
Computers are fast. I'm over simplifying, but if your clock speed is measured in GHz, it can do billions of operations in 1 second. Relatively speaking, 1 second is an eternity, so it is possible it does not change.
If your program is doing regular operation, it is not guaranteed to sample the clock at a random time. Therefore, you don't get a random number.
Don't forget that for a computer, a single second can be 'an eternity'. Programs / algorithms are often executed in a matter of milliseconds. (1000ths of a second. )
The following pseudocode:
for(int i = 0; i < 1000; i++)
n = rand(0, 1000)
fills n a thousand times with a random number between 0 and 1000. On a typical machine, this script executes almost immediatly.
While you typically only initialize the seed at the beginning:
The following pseudocode:
srand(time());
for(int i = 0; i < 1000; i++)
n = rand(0, 1000)
initializes the seed once and then executes the code, generating a seemingly random set of numbers. The problem arises then, when you execute the code multiple times. Lets say the code executes in 3 milliseconds. Then the code executes again in 3 millisecnds, but both in the same second. The result is then a same set of numbers.
For the second point: The author probabaly assumes a FAST computer. THe above problem still holds...
He means by that is you are not able to control how fast your computer or any other computer runs your code. So if you suggest 1 second for execution thats far from anything. If you try to run code by yourself you will see that this is executed in milliseconds so even that is not enough to ensure you got random numbers !

Varying parameters During a simulation in Simulink

I want to change the parameters of a block when the model is running and simultaneously see the changes in the output.
For eg.I have a sine block connected to a Scope.and when i start the simulation.I want to change the frequency of the sine wave and see the corresponding frequency changed wave on the scope output.I want to do this as i want to see how my model behaves for different frequencies.
Somebody please help me in this regard....Please comment and let me know..I will be grateful to who answer my question...
Whether you can vary a parameter during runtime depends on whether that parameter is tunable. Tunable parameters are those that can be changed after the simulation has started, however, you must pause the simulation to be able to do so.
Run your model simulation, then hit the pause button and open up the Sine block dialog. If the frequency edit box is not disabled you can change the frequency and resume the simulation.
If edit box is disabled it means that the frequency is not a tunable parameter. In this case, you can create your own Sine block using a MATLAB function call back and the sin function, by feeding the blocking the desired frequency.
In this particular case, you could use a chirp signal.

Resources