How do I find a pattern in an array
10 views (last 30 days)
Show older comments
So this is what needs to happen, i've created this rythm in Matlab: 1 0 0 1 0 0 1 0 0
Whenever the pattern 1 0 0 occurs I wanna play sound X, 0 1 0 play sound Y and 0 0 1 I want sound Z to play.
This is my code until now:
ritme = 1 0 0 1 0 0 1 0 0
loop = length(ritme)
l = 1;
sound = mat2str(ritme)
bass = "1 0 0"
hihat = "0 1 0"
snare = "0 0 1"
while l <= loop
for i=1:8
if ritme(i) contains(sound,bass);
soundsc(kick,Fs)
elseif ritme(i) contains(sound,hihat);
soundsc(hat,Fs)
elseif ritme(i) contains(sound,snare);
soundsc(snare, Fs)
end
l = l + 1;
pause(0.3)
end
end
0 Comments
Answers (1)
BhaTTa
on 24 Oct 2024 at 17:52
Edited: Walter Roberson
on 24 Oct 2024 at 17:56
Hey @N/A, I assume that each time you compare 3 concecutive numbers from 'ritme' and based on the pattern it matches play that particular sound you can achieve this by making minor changes in your code as suggested below:
% Iterate over the rhythm pattern
for i = 1:(loop - 2)
% Extract a segment of the rhythm pattern
segment = ritme(i:i+2);
% Check which sound to play based on the pattern
if isequal(segment, bass)
% Play the kick sound
soundsc(kick, Fs);
elseif isequal(segment, hihat)
% Play the hi-hat sound
soundsc(hat, Fs);
elseif isequal(segment, snare)
% Play the snare sound
soundsc(snare, Fs);
end
% Pause for a short duration
pause(0.3);
end
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!