フィルターのクリア

Can I write this in a more compact way?

2 ビュー (過去 30 日間)
Timo Kuchheuser
Timo Kuchheuser 2018 年 12 月 15 日
コメント済み: Timo Kuchheuser 2018 年 12 月 16 日
Hi!
Is there a way to write to following statements (the for loop) in a more compact way?
The function
signalSources.generateSineWave
returns a
(ts*fs)x1 double
array. I tried using arrayfun(), but this returns a cell array.
signal = 0;
square_multiples = 1:2:9;
fSquare = @(x)1/x*signalSources.generateSineWave(pitch*x,ts,fs,pi);
for n = square_multiples
signal = signal + fSquare(n);
end
Thank you very much
Timo
  7 件のコメント
Guillaume
Guillaume 2018 年 12 月 16 日
For the record, the way to do it with arrayfun would be:
signal = sum(cell2mat(arrayfun(fsquare, square_multiples.', 'UniformOutput', false)), 1);
since fsquare returns a vector, you're forced to store the outputs into a cell array. The cell array is then converted into a 2D matrix (for that the input array to arrayfun must be a column vector, hence the .'), then the matrix is summed across the rows. Note that the conversion from cell array to matrix involves data copy that you don't have with the explicit loop, so it's likely that cellfun is going to be slower.
Bruno is correct, the proper way to speed up the code is to change the original function so that it creates that 2D matrix directly, without going through a cell array.
Timo Kuchheuser
Timo Kuchheuser 2018 年 12 月 16 日
Thank you!

サインインしてコメントする。

採用された回答

Bruno Luong
Bruno Luong 2018 年 12 月 16 日
編集済み: Bruno Luong 2018 年 12 月 16 日
Cellfun/arrayfun is just disguished for-loop. They are more compact in syntax, less flexible and often slower.
Then the proper way is to vectorize your function as well wrt pitchHz, that returns a 2d array of signal, with the second dimension corresponds to pitchHz then just sum it.
%% Signal parameters
pitch = 440; % Tone pitch
fs = 44100; % Samplerate in Hz
ts = 2; % Duration in seconds
phi = 0; % phase offset
square_multiples = 1:2:9;
harmonic_signal = signalSources.generateSineWave(pitch*square_multiples,ts,fs,pi) ./ square_multiples;
signal = sum( harmonic_signal, 2);
function sine = generateSineWave(pitchHz,tSeconds,fs,phi)
%generateSineWave returns sinusoidal curve with given parameters
% pitchHz frequency in hertz
% tSeconds duration in seconds
% fs sampling rate in hertz
% phi phase offset
l = tSeconds*fs; % length
n = 0:l-1; % normalized time
w = (2*pi/fs)*pitchHz(:); % reshape in column
sine = sin((w.*n)+phi)'; % auto-expansion, use bsxfun for R2016a or prior
end
  1 件のコメント
Timo Kuchheuser
Timo Kuchheuser 2018 年 12 月 16 日
Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatched Filter and Ambiguity Function についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by