How to incorporate multiple IF conditions to generate noisy data?

1 view (last 30 days)
FW
FW on 31 Dec 2020
Commented: Mathieu NOE on 31 Dec 2020
Hello, I wanted to simulate a signal which has noise in the form of spikes (both positive and negative). If a single IF condition is inserted, one can easily generate positive spikes of desired height. Suppose we also wish to insert an additional condition that if n (i) <0, we get a negative spike of magnitude -0.5 in the noise. I have tried several approaches but the vector size of noise increases if I include a separate IF condition. What would be an appropriate way to incorporate both outcomes of IF in one vector with the same size as "t"? Thanks.
t=0:0.01:20;
x=normpdf(t, 10, 0.1); % Gaussian peak
n=rand(1,length(t));
noise=[];
for i=1:length(t)
if(n(i)>=1)
noise=[noise 1.5];
else
noise=[noise 0];
end
end
x=x+noise;
  10 Comments
Mathieu NOE
Mathieu NOE on 31 Dec 2020
Finally , in its simplest form , this will generate timely random positive and negative pulses
the threshold value will modify the amount (density) of pulses (to increase the density , reduce the threshold)
a threshold of 1 is the upper limit but then the pulse density is zero , so you should stay below 1
samples = 1000;
signal = zeros(samples,1);
tmp = 2*(-0.5+rand(samples,1)); % a random signal with amplitude in -1 / +1 range
% positive peaks (multiple)
threshold = 0.97;
time_ind = find(tmp>threshold);
signal(time_ind) = 5;
% negative peaks (multiple)
time_ind = find(tmp<-threshold);
signal(time_ind) = -5;
figure(1),
plot((1:samples),signal,'b');

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 31 Dec 2020
Edited: Adam Danz on 31 Dec 2020
No need for a loop at all.
noise = 1.5*(n>1) + -.5*(n<0)
However, in your example, n is always between 0 and 1.
Demo
rng('default')
n = rand(1,8)*3-1
n = 1×8
1.4442 1.7174 -0.6190 1.7401 0.8971 -0.7074 -0.1645 0.6406
noise = 1.5*(n>1) + -.5*(n<0)
noise = 1×8
1.5000 1.5000 -0.5000 1.5000 0 -0.5000 -0.5000 0
  1 Comment
FW
FW on 31 Dec 2020
Thank you, this is the type of conditional I was looking. Simple as it can be.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by