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

1 次查看(过去 30 天)
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?

采纳的回答

Andrei Bobrov
Andrei Bobrov 2019-11-26
编辑:Andrei Bobrov 2019-11-26
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(:))];

更多回答(1 个)

JESUS DAVID ARIZA ROYETH
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)

类别

Help CenterFile Exchange 中查找有关 Just for fun 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by