필터 지우기
필터 지우기

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matched 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