generate simple sine wave in matlab - matlab

How do I generate a simple sine wave in matlab?
I would like to generate a wave which represents a temperature signal with an amplitude of 15 degrees during a 24 hour period, how can I do this?
t = 1:24
x = 15.*sin(pi*t)
plot(t,x)
where 15 is the amplitude. This does not generate a sine wave as I expected. I was expecting to see one wave which extends over a 24 hour period with an amplitude of 15, say with the lowest value of 5 and a maximum of 20 (how do I include these in the equation?).

Add a constant and adjust frequency:
x = 5 + 15*sin(2*pi*t/24);
In your code the frequency is incorrect, and the sampling period is too large for that frequency: you have aliasing. That's why you don't see a sine wave.

This doesn't have to with Matlab really.
If you'd like to generate a wave with fixed period of, say, T = 24hours you'll have to calculate the sine-function accordingly.
E.g.
t = 1:24;
y = 15 * sin(2*pi*t / T);

Related

Area under curve in MatLab

can anyone tell me how to determine the AUC of the signal shown in the screenshot in Matlab? I would like to determine the AUC above the blue line (demarcation) over the 120 sec. period. Can anyone tell me how to do this in Matlab? Many thanks in advance!
There are a few functions in Matlab to integrate or approximate an integral of a function. Depending on the size of your vector - therefore depending on the sampling rate of that signal - some functions can save you time.
Remove the area under the blue line. So, I assume the y-axis value for the horizontal blue line is positive (x>0). Just subtract the blue line from your original signal and set all negative values to 0.
If y is your signal, x is the cutoff for the blue line (a single number) and it is positive:
y2 = y-x; % subtract blue line
y2(y2<0) = 0; % set negative values to 0
Integrate the resulting y2 curve. You can approximate the integral of the signal with the Trapezoidal numerical integration method from matlab -- trapz function:
But you need to know the sampling rate of the original signal to select the length for the specific 120 seconds.
freq = ?; % Sampling rate in Hz
% For 120 seconds:
sampling _length = 120 * freq;
% select the points for the first 120 seconds and approximate the integral
Q = trapz(y2([1:sampling _length]))
If you want to deepen in this topic:
https://es.mathworks.com/help/matlab/math/integration-of-numeric-data.html

Matlab cos signal from defined frequency course

how come the spectrogram of this code is at its max at approximately 4400Hz instead of 2400Hz in the last timestep of the stft? (frequencyCourse(end) = 100, meshingOrder = 24 -> f = 2400)
startTime = 0; %s
endTime = 30; %s
startIAS = 15; %Hz
endIAS = 100; %Hz
meshingOrder = 24;
fs = 100000; %Hz
t = startTime:1/fs:endTime-1/fs;
frequencyCourse = linspace(startIAS, endIAS, length(t));
signal = cos(2*pi*meshingOrder*frequencyCourse.*t);
spectrogram(signal, hanning(2^13), 0, 2^14, fs, 'yaxis')
Here's a picture:
It works fine as long as I use chirp instead of my self constructed signal, it's not an option though, since more specific courses are to come.
Summary
The problem is that the instantaneous phase is the integral of the instantaneaous frequency with respect to time, not the instantaneous frequency multiplied by time.
You should compute the signal as
signal = cos(2*pi*meshingOrder*cumtrapz(t, frequencyCourse));
What your code does
In your example, you seem to want to generate a linear chirp with initial frequency meshingOrder*startIAS and final frequency meshingOrder*endIAS. But that's not the code is doing.
In your computed signal, the instantaneous phase is the argument to the cos function:
2*pi*meshingOrder*frequencyCourse.*t
Since the variable frequencyCourse increases from meshingOrder*startIAS at start time (which is 0) to meshingOrder*endIAS at end time, this can be expressed as
2*pi*(A+B*t).*t
where A = meshingOrder*startIAS and B = meshingOrder*(endIAS-startIAS)/endTime. Differentiating the instantanous phase with respect to t gives an instantaneous frequency
A + 2*B*t
that is
meshingOrder*startIAS + 2*meshingOrder*(endIAS-startIAS)/endTime * t
As you can see, the problem is the factor 2 here. At end time the instantaneous frequency is
meshingOrder*startIAS + 2*meshingOrder*(endIAS-startIAS)
that is
2*meshingOrder*endIAS - meshingOrder*startIAS
In your example this is 4440 Hz, which is in accordance with your observed value.
What the code should do
For a linear chirp (or a chirp with any other simple frequency variation, such as a quadratic or exponential) you could compute the correct instantaneous phase that gives rise to the desired instantaneous frequency. See for example here. This is also what the chirp function internally does.
But you seem to be want to deal with arbitrary frequency courses. To do that, given arbitrary t, just compute the argument of the cos as the cumulative integral of frequencyCourse with respect to t. This is easily done with cumtrapz:
signal = cos(2*pi*meshingOrder*cumtrapz(t, frequencyCourse));
Changing this line in your example gives the following figure, which has the expected frequency variation from 360 Hz to 2400 Hz:

How can I create n sine waves from the elements of an n-by-m matrix?

I'm writing a program on MATLAB that generates 13 waveforms of varying amplitude, duration, and frequency. Each waveform is repeated 5 times, which means I have 65 'trials' in total.
The total length of each trial = 1.5 ms. The sampling frequency = 4 kHz. I would like the wave to begin at 0.5 ms. Prior to the onset of the wave, and following its offset, I would like the amplitude to be zero (i.e. a 'flatline' prior to and following the wave).
I have created a 65x3 matrix where the columns denote the frequency ('hz'), amplitude ('a'), and duration (ms) of the 65 sine waves. Each row denotes a single wave.
I would like to use the information contained in this 65x3 matrix to generate 65 sine waves of amplitude 'a', frequency 'hz', and duration 'ms'. To be specific: each wave should be created using the parameters (hz,a,ms) specified in the nth row of the matrix. E.g. if row 1 = 100, 1, 50... this means I would like to generate a 100 Hz sine wave (amplitude = 1) lasting 50 ms.
I have attempted to construct a for loop to solve this problem. However, the loop returns a number of errors, and I'm not sure how to resolve them. I have adapted the code to the point where no errors are returned; however, my latest attempt seems to generate 65 waves of equal duration, when in fact the duration of each wave should be that which is stated in vector 'ms'.
Here is my latest, albeit newbie and still unsuccessful, attempt: (note that 'trials' represents the 65x3 matrix discussed above; mA = amplitude).
hz=trials(:,1); mA=trials(:,2); ms=trials(:,3);
trials_waves=zeros(65,500); % the max duration (= 500ms); unsure of this part?
for n = 1:size(order,1)
trials_waves = mA*sin(2*pi*hz*0:ms);
end
Apologies if the information provided is scarce. This is the first time I have asked a question on this website. I can provide more information if needed.
Thank you for your help.
Best,
H
Looks like you've got a good start, I'll try to help you get further towards your solution.
Make a Sine Wave
For starters, let's make a sine wave with variable rate, amplitude, and length.
Fs = 4e3; % sample rate of 4 kHz
Sr = 100; % example rate
Sa = 1; % amplitude
St = 10e-3; % signal duration is 10 ms
% To create a sine wave in MATLAB, I'm going to first create a vector of time,
% `t`, and then create the vector of sine wave samples.
N = St * Fs; % number of samples = duration times sample rate;
t = (1:N) * 1/Fs; % time increment is one over sample rate
% Now I can build my sine wave:
Wave = Sa * sin( 2 * pi * Sr * t );
figure; plot(t, Wave);
Note! This is barely enough time for a full wavelength, so be careful with slow rates and short time lengths.
Make many Sine Waves
To turn this into a loop, I need to index into vectors of input variables. Using my previous example:
Fs = 4e3; % sample rate of 4 kHz
Sr = [100 200 300]; % rates
Sa = [1 .8 .5]; % amplitudes
St = [10e-3 20e-3 25e-3]; % signal durations
nWaves = length(Sr);
N = max(St) * Fs; % number of samples = duration times sample rate;
t = (1:N) /Fs; % time increment is one over sample rate
% initialize the array
waves = zeros(nWaves, N);
for iWaves = 1:nWaves
% index into each variable
thisT = (1:St(iWaves) * Fs) * 1/Fs;
myWave = Sa(iWaves) * sin( 2 * pi * Sr(iWaves) * thisT );
waves(iWaves,1:length(myWave)) = myWave;
end
figure; plot(t, waves);
You still have one more piece, zero padding the front end of your signals, there's lots of ways to do it, one way would be to build the signal the way I've described and then concatenate an appropriate number of zeros to the front of your signal array. Feel free to ask a new question if you get stuck. Good luck!

Should I put sin or cos to represent a sinusoidal signal?

We were asked in an exercise to create a sinusoidal signal of 0.8 seconds with an amplitude of 1 and frequency equal to 100 Hz sampled at 1000 Hz, but in the answer I found:
A=1;fs=100;fe=1000;
te=1/fe;
t=0:te:0.8;
s=A*cos(2*pi*fs*t);
plot(s);
And in another exercise: write a script for a sinusoidal signal of amplitude 1 and 200kHz frequency, over a period N = 64, sampled at 150 kHz, the answer was :
%Signal
fs=200;N=64;
ts=1/fs;
A=1;
subplot(211);
t=0:0.00001:N*ts;
x=sin(2*pi*t*fs);
plot(t,x);
title('signal sinusoidal');
%Sampling
Fe=input('Fe=');
te=1/Fe;
t1=0:te:N*te;
xe=sin(2*pi*t1*fs);
subplot(212);
stem(t1,xe);
I'm so confused. When to put a sin and when to put a cosine? My question is why they put a cosine instead of a sin? Is there some kind of rule behind it?
Thanks in advance.
Any of those choices qualifies as a sinusoid. Note that
cos(2*pi*fs*t)
is the same as
sin(2*pi*fs*t + pi/2)
In general,
sin(2*pi*fs*t + phi)
is a sinusoid for any choice of phi (as would be cos(2*pi*fs*t + phi)) . phi is the initial phase (or simply phase) of the sinusoid. To know which phi to use you would need an additional condition.

Count the number of Cos and sine waves in a raw signal

I am trying to generate a score or a number which represents how many cos and sin waves can generate my signal. For example, if the signal is a sine wave this means it is 100% pure as it can be generated by only one sine signal, if it consists of two sine wave .. this means it is not pure wave and if it consists 100 sine waves it is really unpure and so on .... I tried FFT and FS but it didn't work ... Can anyone help me ??
FFT will work.
You must process wave with Fourier Transform, then calculate the magnitude
sqrt(real*real + image*image). Counting the peaks of result will provide you number of sinewaves with different frequency.
Here you go:
x = s;
X = dct(x);
[XX,ind] = sort(abs(X),'descend');
i = 1;
while norm(X(ind(1:i)))/norm(X)<0.99
i = i + 1;
end
Needed = i;