%% Manipulate Array of MIDI Messages
% In this example, you create an array of MIDI messages, and then index into the array in a loop to define a melody.
%
% Create a 22-by-1 array of MIDI messages with all zero data.

msgArray = midimsg([22,1]);

% To create a melody, create MIDI NoteOn and NoteOff messages by indexing in a loop. Display the result.

melody = [60,65,60,57,55,53,60,65,60,67,60];
for i = 1:numel(melody)
    idx = (2*i-1):(2*i);
    msgArray(idx) = midimsg('Note',1,melody(i),50,0.5,i);
end
msgArray

% The order of the MIDI messages in the array is only important for readability. When you send MIDI messages using a mididevice object, the mididevice object reorders your MIDI messages according to their timestamps and sends them in chronological order. Create a PitchBend MIDI message to bend the fourth note downward and add it to the MIDI message array. For readability, sort the MIDI message array by Timestamp.

msg = midimsg('PitchBend',1,7192,4.01);
msgArray = [msgArray;msg]
timeStamps = [msgArray.Timestamp];
[~,idx] = sort(timeStamps);

msgArray = msgArray(idx)

% Copyright 2012 The MathWorks, Inc.