Revision as of 17:19, 28 April 2019 by Nlaten (Talk | contribs)

How to Recreate any Melody in MATLAB


Utilizing both exponential and sine functions in MATLAB, you can recreate your favorite melody in MATLAB!
However, to do this you will need to first choose the frequency for each of your notes, the length that each note will be played, and the order in which these notes will be played in the song. As an example, one could consider the common I-V-vi-IV progression. If you were to play this, a common combination of notes is C-G-A-F. This combination of notes is used in many popular songs you may have heard of, such as, Journey – “Don't Stop Believing”, James Blunt – “You're Beautiful”, Black Eyed Peas – “Where Is the Love”, Alphaville – “Forever Young”, Jason Mraz – “I'm Yours”, and Train – “Hey Soul Sister”. Since this is such a catchy tune, it would be interesting to see how we can code this in MATLAB. So that is what I did, if we were to take this and create it in MATLAB the code would look like this.

Code


notes = {'C' 'G' 'A' 'F'}; %notes which will be used
freq = [261.60 391.99 440.00 349.23]; %frequencies of notes above
melody = {'C' 'G' 'A' 'F' 'C' 'G' 'A' 'F'}; %four chords played twice
a = [];

%For Loop
for k = 1:numel(melody); %for loop which will create the melody
note = 0:0.00025:1.0; %note duration (which can be edited for length)
a = [a sin(2*pi*freq(strcmp(notes,melody{k}))*note)]; %a will create the melody given variables defined above
end

sound(a); % plays the melody
%End of code


Conclusion


In conclusion, using this format of MATLAB code, you should be able to create any song as long as the notes are available online. Just change the notes line of code as well as the frequency line of code to match the notes being used. Once all necessary notes are added, the melody can be changed to match the song and your song should be able to play in MATLAB. Also if the length of the notes is not the way you like, you can edit the note line in the code to match the length you desire. It may not sound perfect, as MATLAB just plays the frequency that the note is, however it will play the correct note as long as you have defined it correctly. Now that you know how to play any song or melody in MATLAB, test it out with your favorite song and show it off to your friends and family!


References and Helpful Links


Songs using I-V-vi-IV progression - https://en.wikipedia.org/wiki/List_of_songs_containing_the_I%E2%80%93V%E2%80%93vi%E2%80%93IV_progression Frequency for Notes - http://pages.mtu.edu/~suits/notefreqs.html MATLAB help - https://www.mathworks.com/help/matlab

Alumni Liaison

Basic linear algebra uncovers and clarifies very important geometry and algebra.

Dr. Paul Garrett