For each value in a vector, find the closest value in a cell and return index

2 vues (au cours des 30 derniers jours)
I have a vector of sampled frequency values:
sampled_freqs = [495 393 589]
And a cellular array that has the names of the musical notes in one column and their frequencies in another.
cell = {G4, 392; A4, 440; B4, 493.88; C5, 523.25, D5, 587.33}
The actual cellular array contains all the musical note frequencies. For each sampled frequency, I would like to return the closest musical note and its "true" frequency from the cellular array. The return data type can be whatever you think would be most practical to graph as a pure sin wave and play back as individual notes. (The end state is to take a recorded audio signal, break it into its component frequencies, and recreate it with pure tones.)
I attempted to find the appropriate cells with the following code:
for i = 1:length(sampled_freqs)
[~,ClosestFreq] = min(cellfun(@(x)min(abs(x-sampled_freqs(i))),cell));
disp(ClosestFreq)
end
However this wasn't returning the musical notes I wanted.
In addition to finding out how to properly return the desired values from the cellular array, I would also like to know if this would be easier to do if the data was of a different data type? Which data type would be better?

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 26 Nov 2019
Modifié(e) : Andrei Bobrov le 26 Nov 2019
sampled_freqs = [495 393 589];
cll = {'G4', 392; 'A4', 440; 'B4', 493.88; 'C5', 523.25; 'D5', 587.33};
[~,i] = min(abs(cat(1,cll{:,2}) - sampled_freqs(:)'));
out = [cll(i,:),num2cell(sampled_freqs(:))];

Plus de réponses (1)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH le 26 Nov 2019
a better way:
sampled_freqs = [495 393 589];
values =[392, 440, 493.88, 523.25,587.33];
names={'G4' 'A4' 'B4' 'C5' 'D5'};
[~,idx]=min(abs(repmat(values,numel(sampled_freqs),1)-sampled_freqs'),[],2);
valuesnotes=values(idx)
namenotes=names(idx)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by