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

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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. If we were to take this and create it in MATLAB the code may 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 k = 1:numel(melody); %for loop which will create the melody
note = 0:0.00025:0.5; %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



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. 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!

Alumni Liaison

Prof. Math. Ohio State and Associate Dean
Outstanding Alumnus Purdue Math 2008

Jeff McNeal