MATLAB 循环重构
MATLAB loop refactoring
我很想知道是否有更好的方式来表达以下循环:
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
非常感谢任何建议。新年快乐!
在 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,默认情况下沿矩阵的第一维求和,结果将是与 t
大小相同的行向量。
signal_synth = sum(a(:) .* cos(2 * pi * f(:) .* t + p(:)));
使用矩阵乘法的更紧凑的形式:
signal_synth = a(:).' * cos(2 * pi * f(:) .* t + p(:));
我很想知道是否有更好的方式来表达以下循环:
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
非常感谢任何建议。新年快乐!
在 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,默认情况下沿矩阵的第一维求和,结果将是与 t
大小相同的行向量。
signal_synth = sum(a(:) .* cos(2 * pi * f(:) .* t + p(:)));
使用矩阵乘法的更紧凑的形式:
signal_synth = a(:).' * cos(2 * pi * f(:) .* t + p(:));