I'm curious to know if there is a better way to express the following loop:
To = 1;
fileName = "fourier/signal.txt";
spectrum_left(abs(spectrum_left) < 1e-3) = 0 0i;
Ts = 1 / Fs;
t = 0:Ts:To-Ts;
signal = load(fileName, "-ascii");
Ns = numel(signal);
Fs = Ns / To;
fr = f(abs(spectrum_left) > 0)
a = abs(spectrum_left(abs(spectrum_left) > 0))
p = angle(spectrum_left(abs(spectrum_left) > 0))
signal_synth = 0;
len = length(a);
for i=1:len
a_i = a(i);
p_i = p(i);
f_i = fr(i);
s_i = a_i * cos(2*pi*f_i*t p_i)
signal_synth = signal_synth s_i;
end
Any suggestions are greatly appreciated. And Happy New Year!
CodePudding user response:
In MATLAB, element-wise operators, that preceded by the period character (.), can be applied on arrays. I used (:) operator to convert the vectors to column vectors. Note that t is a row vector, when it is combined with column vectors the result will be a matrix that is formed by implicit expansion. In order to sum up the values the function sum is used that by default sums along the first dimension of the matrix and the result will be a row vector with the same size as t.
signal_synth = sum(a(:) .* cos(2 * pi * f(:) .* t p(:)));
A more compact form using matrix multiplication:
signal_synth = a(:).' * cos(2 * pi * f(:) .* t p(:));
