MATLAB: How to incorporate multiple IF conditions to generate noisy data

if statementnoise

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;

Best Answer

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