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

1 回表示 (過去 30 日間)
Shawn Cooper
Shawn Cooper 2019 年 11 月 26 日
編集済み: Andrei Bobrov 2019 年 11 月 26 日
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
JESUS DAVID ARIZA ROYETH 2019 年 11 月 26 日
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 Center および File ExchangeJust for fun についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by