i want to plot flat-topped PAM of sinusoid. wave using matlab.
the sinusoidal signal has frequency = 10^4/(2*pi) HZ and sampling frequency = 8 kHZ. pulse duration T = 50 microseconds.
i wrote code for natural sampling, so how to do flat-top?
clear all;
close all;
Fs = 1e9;
t = 0:1/Fs:(0.2e-2);
fc = 8000; %sampling frequency
fm = 10^4/(2*pi); %message frequency
a = 1;
vm = a.*sin(2*pi*fm*t); %message
pulseperiods = [0:10]*1/fc;
pulsewidth = 50e-6;
vc = pulstran(t,pulseperiods,#rectpuls,pulsewidth);
y = vc.*vm;
figure
subplot(3,1,1);
plot(t,vm); % plot message
xlabel('Temps');
ylabel('Amplitude');
title('Message');
subplot(3,1,2);
plot(t,vc); % plot pulse
xlabel('Temps');
ylabel('Amplitude');
title('Switching waveform');
subplot(3,1,3);
plot(t,y); % plot PAM naturel
xlabel('Temps');
ylabel('Amplitude');
title('PAM naturel');
The flat-top PAM means the instantaneous sampling, i.e. the message signal is sampled only once per period, so modulated signal does not change its value until returning to zero and next sampling period. The sampling takes place at rising edge of carrier signal, so the solution is quite straightforward: by adding the for loop to your code:
for i = 2:length(t)
if vc(i) == 1 && vc(i-1) == 0 %if the rising edge is detected
y1(i) = vc(i) * vm(i); %sampling occurs
elseif vc(i) == 1 && vc(i-1) == 1 %and while the carrier signal is 1
y1(i) = y1(i-1); %the value of y1 remains constant
else
y1(i) = 0; %otherwise, y is zero
end
end
plot(t,y1); % flat-top PAM plot
xlabel('Temps');
ylabel('Amplitude');
title('PAM flat-top');
you get
Related
So I have an initial velocity iv a final velocity fv (that is always 0) a time t and an acceleration variable a
I use these variables to calculate final distance fd
Note: language used here is Kotlin
Note: Formula used for calculating fd and a are not something I came up with
var iv = 10.0 // initial velocity
var fv = 0.0 // final velocity
var t = 8.0 // time
var a = ((fv - iv)/t) // acceleration
var fd: Double = ((iv*t) + (a/2.0*Math.pow(t,2.0)))
I get the result that fd = 40.0
when I try to model this the way I would try to apply it in code.
var d = 0.0 // current distance traveled
var i = 0 // current time elapsed
while (i < t) {
d += v
v += a
i++
}
I end up with the result of d = 45.0 when d should equal fd at the end.
what am I doing wrong in applying velocity and acceleration to velocity so that my results differ from what the mathematical formulas show they should be?
Don't worry about "formulas" - think about the physics.
If you have ever studied calculus and physics you know that:
a = dv/dt // a == acceleration; v == velocity; t == time
v = ds/dt // v == velocity; s == distance; t == time
If you know calculus well enough you can integrate the equation for acceleration twice to get the distance traveled as a function of time:
a(t) = dv/dt = a0
v(t) = ds/dt = a0*t + v0
s(t) = (a0/2)*t^2 + v0*t + s0
You can calculate the constants:
a0 = -1.25 m/sec^s
v0 = 10 m/s
s0 = 0 m
Substituting:
a(t) = -1.25
v(t) = 10 - 1.25*t
s(t) = -0.625*t^2 + 10*t = (10 - 0.625*t)*t
You can also calculate the answer numerically. That's what you're doing with Kotlin.
If you know the initial conditions
a(0), v(0), and s(0)
you can calculate the value at the end of a time increment dt like this:
a(t+dt) = f(t+dt)
v(t+dt) = v(t) + a(t)*dt
s(t+dt) = s(t) + v(t)*dt
Looks like you are assuming that acceleration is constant throughout the time you're interested in.
You don't say what units you're using. I'll assume metric units: length in meters and time in seconds.
You decelerate from an initial velocity of 10 m/sec to a final velocity of 0 m/second over 8 seconds. That means a constant acceleration of -1.25 m/sec^2.
You should be able to substitute values into these equations and get the answers you need.
Do the calculations by hand before you try to code them.
I am tring to get magnitud squared coherence (MSC) and I am finding some problems.
In theory, the MSC is the result of the crospectra of two signals, devided by the autospectra of each signal.
Therefore, this is my code:
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sampling period
L = length(myData(1,:)); % length of segment
Hz = Fs*(0:(L/2))/L; % frequency vector
dat1 = fft(myData(1,:));
dat2 = fft(myData(2,:));
pow1 = dat1.*conj(dat1); % autospectra signal 1
pow2 = dat2.*conj(dat2); % autospectra signal 2
cpow = abs(dat1.*conj(dat2)).^2; % crosspectra
coh = cpow./(pow1.*pow2); % getting the coherence
coherence = coh(1:L/2+1);
coherence(2:end-1) = coherence(2:end-1); % adjusting length to Nyquest freq
figure;
plot(Hz,coherence)
but the result are only "1" and it does not make much seance, so there must be I mistake but I just can't find it.
Thanks for your help
So I'm trying to animate a fake heartbeat for my Android wear watchface. I have an API that grabs the heartrate in BPM and the current millisecond now I'm trying to use an equation to make an image "beat" to the BPM. Here's the psuedocode:
IF (Millis / HeartRate) % (1000 / HeartRate) <= 1)
Opacity = 100;
ELSE
Opacity = 75;
ENDIF
I'm really not sure if I calculated it properly. I don't think the image is properly flashing at the correct rate. Any help with the math would be appreciatred!
A value in BPM is a frequency, rather than a period of time:
b BPM = b / 60s = b/60 * s^-1
The period of the oscillation is
T = 1/f = 60s / b = 60/b s
If we have a time in milliseconds, then we can work out the modulo vs the period:
remainderInSeconds = CurrentTimeInSeconds % T
= (CurrentTimeInMilliseconds * 1e-3) % T
= (CurrentTimeInMilliseconds * 1e-3) % (60/BeatsPerMinute)
fraction = remainderInSeconds / Period
= [(CurrentTimeInMilliseconds * 1e-3) % T] / T
= (CurrentTimeInMilliseconds * 1e-3 / T) % 1
= (CurrentTimeInMilliseconds * 1e-3 / (60/BeatsPerMinute)) % 1
= (CurrentTimeInMilliseconds * 1e-3 * BeatsPerMinute / 60)) % 1
= (CurrentTimeInMilliseconds * BeatsPerMinute / 60e3)) % 1
Then you can check whether the fraction is below your threshold; if you want the pulse to last a 20th of the period, then check if fraction < 1/20.
Alternatively just calculate the remainder in seconds, if you want the pulse to last a specific amount of time rather than a portion of the period.
I managed to compile a new code using a different variable from the watch API. This other variable is essentially a number between 0 and 359 which steps up at mere decimals per frame. (The variable is normally used for a smooth motion second hand).
I also decided to use a sine wave and RGB shaders instead of opacity. Here is the new code
Green = 0
Blue = 0
Red = 100 * math.sin(HeartRate * SecondsRotationSmooth / 60)
Using this particular variable isn't ideal, but it at least gives me a better looking code. If anyone wants to give a better answer please do!
After studying the vectorization methods used in the two links below, I've attempted to create a simple trading strategy template (code shown below) that can be vectorized in R for better speed vs a loop-based structure. I'm having difficulty vectorizing because variable state must be maintained and built upon such as:
1) The signals I'm using are not mutually exclusive for long and short (as in a simplistic MA crossover system).
2) Once triggered, the signal can wander until it gets an opposing indication (such as an RSI go short above 80, go long below 20 type system).
3) Positions are held for multiple periods so it isn't a case of enter on every signal or exit after a signal is false (I wish to be able to only enter once as in a Stop and Reverse or SAR system).
I consider this to be a simple example system but it is a bit more complex than the examples listed here:
http://blog.fosstrading.com/2011/03/how-to-backtest-strategy-in-r.html
Cumulative Return in Trading Strategy Test
System logic summary: The system starts flat then goes long (short) at the ask (bid) price when zscore is below (above) -2 (2). The system keeps track of performance statistics such as 'trades', 'wins', closed P&L (others omitted for simplicity). The system also keeps a running 'equity' for plotting after a system run.
# assume vectors bid, ask, and zscore containing those price series respectively
# pos = current position where 1 == long, -1 == short, 0 == flat
# entryP = entry price, pnl = open pnl, cpnl = closed pnl
pos = 0; entryP = 0.0; pnl = 0; cpnl = 0; trades = 0; wins = 0
ub = length(bid)
equity = rep(0, ub)
for (i in 10000:ub) {
pnl = 0
if (pos > 0) pnl = bid[i] - entryP
if (pos < 0) pnl = entryP - ask[i]
if (zscore[i] > 2.0 && pos != -1) { # go short
if (pos > 0) { # exit long and record pnl
cpnl = cpnl + pnl
if (pnl > 0) wins = wins + 1
trades = trades + 1
pnl = 0
}
pos = -1
entryP = bid[i]
} else if (zscore[i] < -2.0 && pos != 1) { # go long
if (pos < 0) { # exit short and record pnl
cpnl = cpnl + pnl
if (pnl > 0) wins = wins + 1
trades = trades + 1
pnl = 0
}
pos = 1
entryP = ask[i]
}
equity[i] = cpnl + pnl
}
# assume close-out of final position
cpnl = cpnl + pnl
if (pnl > 0) wins = wins + 1
if (pos != 0) trades = trades + 1
# plot equity chart and report performance stats
plot(equity, t='l', lwd=3)
cpnl;trades; cpnl / trades; wins/trades
Is it possible to vectorize this simple loop-based mean reversion trading system in R?
" I'm having difficulty vectorizing because variable state must be maintained "
That sums it all. You can't avoid loops if your result in any iteration depends on previous iterations.
With a sine input, I tried to modify it's frequency cutting some lower frequencies in the spectrum, shifting the main frequency towards zero. As the signal is not fftshifted I tried to do that by eliminating some samples at the begin and at the end of the fft vector:
interval = 1;
samplingFrequency = 44100;
signalFrequency = 440;
sampleDuration = 1 / samplingFrequency;
timespan = 1 : sampleDuration : (1 + interval);
original = sin(2 * pi * signalFrequency * timespan);
fourierTransform = fft(original);
frequencyCut = 10; %% Hertz
frequencyCut = floor(frequencyCut * (length(pattern) / samplingFrequency) / 4); %% Samples
maxFrequency = length(fourierTransform) - (2 * frequencyCut);
signal = ifft(fourierTransform(frequencyCut + 1:maxFrequency), 'symmetric');
But it didn't work as expected. I also tried to remove the center part of the spectrum, but it wielded a higher frequency sine wave too.
How to make it right?
#las3rjock:
its more like downsampling the signal itself, not the FFT..
Take a look at downsample.
Or you could create a timeseries object, and resample it using the resample method.
EDIT:
a similar example :)
% generate a signal
Fs = 200;
f = 5;
t = 0:1/Fs:1-1/Fs;
y = sin(2*pi * f * t) + sin(2*pi * 2*f * t) + 0.3*randn(size(t));
% downsample
n = 2;
yy = downsample([t' y'], n);
% plot
subplot(211), plot(t,y), axis([0 1 -2 2])
subplot(212), plot(yy(:,1), yy(:,2)), axis([0 1 -2 2])
A crude way to downsample your spectrum by a factor of n would be
% downsample by a factor of 2
n = 2; % downsampling factor
newSpectrum = fourierTransform(1:n:end);
For this to be a lower-frequency signal on your original time axis, you will need to zero-pad this vector up to the original length on both the positive and negative ends. This will be made much simpler using fftshift:
pad = length(fourierTransform);
fourierTransform = [zeros(1,pad/4) fftshift(newSpectrum) zeros(1,pad/4)];
To recover the downshifted signal, you fftshift back before applying the inverse transform:
signal = ifft(fftshift(fourierTransform));
EDIT: Here is a complete script which generates a plot comparing the original and downshifted signal:
% generate original signal
interval = 1;
samplingFrequency = 44100;
signalFrequency = 440;
sampleDuration = 1 / samplingFrequency;
timespan = 1 : sampleDuration : (1 + interval);
original = sin(2 * pi * signalFrequency * timespan);
% plot original signal
subplot(211)
plot(timespan(1:1000),original(1:1000))
title('Original signal')
fourierTransform = fft(original)/length(original);
% downsample spectrum by a factor of 2
n = 2; % downsampling factor
newSpectrum = fourierTransform(1:n:end);
% zero-pad the positive and negative ends of the spectrum
pad = floor(length(fourierTransform)/4);
fourierTransform = [zeros(1,pad) fftshift(newSpectrum) zeros(1,pad)];
% inverse transform
signal = ifft(length(original)*fftshift(fourierTransform),'symmetric');
% plot the downshifted signal
subplot(212)
plot(timespan(1:1000),signal(1:1000))
title('Shifted signal')
Plot of original and downshifted signals http://img5.imageshack.us/img5/5426/downshift.png