# Generating a realistic sine wave in MATLAB

I'm working on a simulation on MATLAB and I need a realistic sine wave which has harmonics. So I know there would be harmonics at 2f,3f... but I am not sure how to determine their amplitude. I tried to use Fourier and Bessel expansion, but I'm not sure about their implementation on MATLAB.

What can I use for that purpose? Any advice appreciated.

• A sine wave has no harmonics. You want some other waveform. All periodic waveforms can be created as the sum of a sine harmonic series. If the waveform is symmetric along the time axis then it will have only odd harmonics. Dec 6, 2018 at 7:01
• I believe in reality it has harmonics. You cant find a perfect sine wave. Additionally, in reality it also has even harmonics. Dec 6, 2018 at 7:09
• @Ziya Zeskin, a sine wave is perfect by definition. When a wave is not a perfect sine, it has harmonics. When it has harmonics, is is not perfect. Applying fourier analysis to a sine yields only the base frequency.
– Bart
Dec 6, 2018 at 7:18
• I think you are trying to ask something like, "How, in MATLAB, can I generate an asymmetric distorted sine wave (so that I get both odd and even harmonics)?" (I have no idea as I have never seen the program.) Dec 6, 2018 at 7:26
• I think it might be worthwhile to take a step back and ask why you are generating a realistic sine wave which, according to your notion contains harmonics. What will you be using it for? My suspicion is that you are in need of overall guidance, rather than help with this one small issue of how do you add harmonics (distortion) to a clean sine wave. The commenters are definitely trying to help. It is just that it is hard to understand what you are doing. Dec 6, 2018 at 8:01

## 1 Answer

I have two approaches to do that when working in MATLAB.

The first is to generate a clean sine wave, and then apply a distorting function. For instance applying x*(1+kx^2) for small k to your sinewave vector x would give small amounts of even harmonics. Use v^3 for odd harmonics. k=0 gives the original signal vector, increase k for more distortion. I don't usually calibrate what k does, just fft and see what it's given me, and adjust k to taste.

The second is to inverse fourrier transform a vector containing your frequency specification. So you'd create a vector like [dc_val, 1, second_level, third level, ... ], and then apply ifft to turn it into a time vector. Note that MATLAB is one of the few languages still stuck in the BASIC and FORTRAN dark ages by using 1-based arrays. This means the dc term is index 1, sine term 2, 2nd harmonic 3 etc.

Note the frequency specification vector is complex, so you may get an unrealistic looking waveform if you use real coefficients for all your harmonics, and they all add up in phase Gibbs-style. If that's not acceptable, the kludge is to add a random phase to each frequency component before transformation.