Can I write this in a more compact way?
4 次查看(过去 30 天)
显示 更早的评论
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
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.
采纳的回答
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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!