Какие функции реализуют операторы freqs feedback
Перейти к содержимому

Какие функции реализуют операторы freqs feedback

  • автор:

Функции matlab для расчета линейных систем (цепей).

Пакет Signal Processing содержит функции позволяющие выполнять расчет линейных систем. В частности они позволяют выполнить расчет комплексного коэффициента передачи, амплитудно-частотную и фазо-частотную характеристики системы, а также осуществить преобразование способов описания линейных систем.

Для расчета комплексного коэффициента передачи в функцию передачи необходимо подставить мнимый аргумент׃

S = Jω.

Соответствующие расчеты выполняются с помощью функции freqs. Простейший вид синтаксиса: freqs (b,a);

Здесь b и a – векторы коэффициентов полиномов соответственно числителя и знаменателя функции передачи. Коэффициенты следуют в порядке убывания степеней, заканчивая постоянным слагаемым.

Для расчета характеристик по умолчанию выбирается 200 частот, логарифмически равномерно распределенных в диапазоне от 0,1 до 10.

При отсутствии выходных параметров функция freqs строит графики АЧХ и ФЧХ.

АЧХ выводится в логарифмическом масштабе (без пересчета в децибелы), ФЧХ – в градусах.

Если вместо графика нужно получить вектор рассчитанных значений комплексного коэффициента передачи, нужно присвоить результат, возвращаемый функцией freqs, какой либо переменной:

h = freqs (b,a);

Если использовать второй выходной параметр, то в нем функция возвращает вектор частот, для которых рассчитаны значения импульсной характеристики׃

[h, w] = freqs (b,a);

Можно построить вектор значений частотной характеристики АЧХ в линейном , а не в логарифмическом масштабе:

» [h, w] = freqs (b, a)

» plot (w, abs (h))

»grid on

Частотный диапазон можно задать принудительно также с помощью третьего входного параметра, которым является вектор круговых частот w׃

h = freqs (b, a, w);

Функция unwrap позволяет избавиться лишних разрывов ФЧХ. Она ищет в переданном ей векторе скачки между соседними элементами, превышающими заданную пороговую величину (по умолчанию π) и сдвигает соответствующие фрагменты вектора на ±2π нужное число раз

» [h, w] = freqs (b, a); % — ФЧХ

» phi = angle (h)

» phi = unwrap (phi) % — устранение скачков

» plot (w, phi * 180/ pi) % отображается в градусах

» grig on

Функции преобразования способов описания систем.

В пакете Signal Processing системы MATLAB имеется ряд функций, предназначенных для преобразования описаний из одной формы в другую.

Имена функций имеют вид XX2YY, где XX – обозначение исходной формы описания, а YY – обозначение целевой формы описания системы.

Формы описания цепей в именах функций׃

tf – (transfer function) – коэффициенты полинома числителя и знаменателя функции передачи H (s);

— zp – нули и полюсы (zeros and poles);

ss – описание в пространстве состояний (state-space).

Необходимость в преобразовании описаний часто возникает из-за того, что функции, например фильтров, дают результат расчета в одной форме, а функция построения, например частотной характеристики, в другой форме.

Для входных и выходных параметров используются следующие обозначения:

а) функция передачи – в – вектор-строке коэффициентов (в порядке убывания степеней) числителя функции передачи;

а – вектор-строке коэффициентов (в порядке степеней) знаменателя функции передачи;

б) нули и полюсы׃

z – вектор нулей (столбец);

p – вектор полюсов (столбец);

K — коэффициент усиления (скаляр).

в) Пространство состояний׃

A— квадратная матрица связи вектора состояний и его производной;

B вектор-столбец связи входных сигналов и производный вектора состояний;

C — вектор-строка связи выходных сигналов и вектора состояний;

D — скалярный коэффициент связи выходных и входных сигналов.

Дадим пояснения функций преобразования.

Функция tf2zp преобразует наборы коэффициентов полиномов числителя, знаменателя функции передачи в векторы нулей и полюсов, рассчитывая также значения общего коэффициента усиления

[z, p, K] = tf2zp (b, a);

Коэффициент усиления рассчитывается из соотношения

Функция zp2tf является обратной по отношению к функции tf2zp׃ она осуществляет преобразование коэффициента усиления, векторов нулей и полюсов функций передачи в коэффициенты полиномов её числителя и знаменателя׃

[b, a] = zp2tf (z, p, K);

Функция tf2ss преобразует наборы коэффициентов полиномов числителя и знаменателя функции передачи в параметры представления системы в пространстве состояний׃

[A, B, C, D] = tf2ss (b, a);

Функция ss2tf является обратной по отношению к функции tf2ss׃ она преобразует параметры пространства состояний в коэффициенты полиномов функции передачи системы׃

[b, a] = ss2tf (A, B, C, D);

Функция zp2ss преобразует нули, полюсы и коэффициенты усиления в ее параметры пространства состояний׃

[A, B, C, D] = zp2ss;

Функция ss2zp является обратной по отношению к предыдущей, т.е. она преобразует параметры пространства состояний в нули, полюсы и коэффициенты усиления׃

Русские Блоги

[MATLAB] Введение в функцию freqz (частотная характеристика цифрового фильтра)

freqz

Frequency response of digital filter

Syntax

Description

[ h , w ] = freqz( b,a , n ) returns the n -point frequency response vector, h , and the corresponding angular frequency vector, w , for the digital filter with numerator and denominator polynomial coefficients stored in b and a , respectively.

[h, w] = freqz (b, a, n) возвращает n-точечный вектор частотной характеристики h и соответствующий вектор угловой частоты w цифрового фильтра, где полиномиальные коэффициенты числителя и знаменателя сохраняются в b и a, соответственно.

[ h , w ] = freqz(___, n ,’whole’) returns the frequency response at n sample points around the entire unit circle.

[ h , w ] = freqz(___, n ,’whole’) Возвращает частотную характеристику n точек выборки вокруг всего единичного круга.

Frequency Response from Transfer Function

Compute and display the magnitude response of the third-order IIR lowpass filter described by the following transfer function:

Express the numerator and denominator as polynomial convolutions. Find the frequency response at 2001 points spanning the complete unit circle.

[ h , w ] = freqz( d , n ) returns the n -point complex frequency response for the digital filter, d .

Frequency Response of an FIR Bandpass Filter

Design an FIR bandpass filter with passband between and rad/sample and 3 dB of ripple. The first stopband goes from 0 to rad/sample and has an attenuation of 40 dB. The second stopband goes from rad/sample to the Nyquist frequency and has an attenuation of 30 dB. Compute the frequency response. Plot its magnitude in both linear units and decibels. Highlight the passband.
sf1 = 0.1;
pf1 = 0.35;
pf2 = 0.8;
sf2 = 0.9;
pb = linspace(pf1,pf2,1e3)*pi;

bp = designfilt(‘bandpassfir’, .
‘StopbandAttenuation1’,40, ‘StopbandFrequency1’,sf1.
‘PassbandFrequency1′,pf1,’PassbandRipple’,3,’PassbandFrequency2′,pf2, .
‘StopbandFrequency2′,sf2,’StopbandAttenuation2’,30);

[h,w] = freqz(bp,1024);
hpb = freqz(bp,pb);

subplot(2,1,1)
plot(w/pi,abs(h),pb/pi,abs(hpb),’.-‘)
axis([0 1 -1 2])
legend(‘Response’,’Passband’,’Location’,’South’)
ylabel(‘Magnitude’)

subplot(2,1,2)
plot(w/pi,db(h),pb/pi,db(hpb),’.-‘)
axis([0 1 -60 10])
xlabel(‘Normalized Frequency (\times\pi rad/sample)’)
ylabel(‘Magnitude (dB)’)

freqz(___) with no output arguments plots the frequency response of the filter.

Frequency Response of an FIR filter

Design an FIR lowpass filter of order 80 using a Kaiser window with . Specify a normalized cutoff frequency of rad/sample. Display the magnitude and phase responses of the filter.

b = fir1(80,0.5,kaiser(81,8));
freqz(b,1)

Design the same filter using designfilt. Display its magnitude and phase responses using fvtool.
d = designfilt(‘lowpassfir’,’FilterOrder’,80, .
‘CutoffFrequency’,0.5,’Window’,<'kaiser',8>);
freqz(d)

Note: If the input to freqz is single precision, the frequency response is calculated using single-precision arithmetic. The output, h , is single precision.

[ h , w ] = freqz( sos , n ) returns the n -point complex frequency response corresponding to the second-order sections matrix, sos .

[ h , f ] = freqz(___, n , fs ) returns the frequency response vector, h , and the corresponding physical frequency vector, f , for the digital filter with numerator and denominator polynomial coefficients stored in b and a , respectively, given the sample rate, fs .

[ h , f ] = freqz(___, n ,’whole’, fs ) returns the frequency at n points ranging between 0 and fs .

h = freqz(___, w ) returns the frequency response vector, h , at the normalized frequencies supplied in w .

h = freqz(___, f , fs ) returns the frequency response vector, h , at the physical frequencies supplied in f .

Какие функции реализуют операторы freqs feedback

Какие функции реализуют операторы freqs feedback

Frequency response of analog filters

Description

freqs returns the complex frequency response H(j) (Laplace transform) of an analog filter

given the numerator and denominator coefficients in vectors b and a .

h = freqs(b,a,w) returns the complex frequency response of the analog filter specified by coefficient vectors b and a . freqs evaluates the frequency response along the imaginary axis in the complex plane at the angular frequencies in rad/sec specified in real vector w , which must contain more than one frequency.

[h,w] = freqs(b,a) automatically picks a set of 200 frequency points w on which to compute the frequency response h .

[h,w] = freqs(b,a,f) picks f number of frequencies on which to compute the frequency response h .

freqs with no output arguments plots the magnitude and phase response versus frequency in the current figure window.

freqs works only for real input systems and positive frequencies.

Find and graph the frequency response of the transfer function given by:

You can also create the plot with:

To convert to hertz, degrees, and decibels, use:

freqs evaluates the polynomials at each frequency point, then divides the numerator response by the denominator response:

[MATLAB] Введение в функцию freqz (частотная характеристика цифрового фильтра)

freqz

Frequency response of digital filter

Syntax

Description

[ h , w ] = freqz( b,a , n ) returns the n -point frequency response vector, h , and the corresponding angular frequency vector, w , for the digital filter with numerator and denominator polynomial coefficients stored in b and a , respectively.

[ h , w ] = freqz(___, n ,’whole’) returns the frequency response at n sample points around the entire unit circle.

Frequency Response from Transfer Function

Compute and display the magnitude response of the third-order IIR lowpass filter described by the following transfer function:

Express the numerator and denominator as polynomial convolutions. Find the frequency response at 2001 points spanning the complete unit circle.

[ h , w ] = freqz( d , n ) returns the n -point complex frequency response for the digital filter, d .

Frequency Response of an FIR Bandpass Filter

Design an FIR bandpass filter with passband between and rad/sample and 3 dB of ripple. The first stopband goes from 0 to rad/sample and has an attenuation of 40 dB. The second stopband goes from rad/sample to the Nyquist frequency and has an attenuation of 30 dB. Compute the frequency response. Plot its magnitude in both linear units and decibels. Highlight the passband.
sf1 = 0.1;
pf1 = 0.35;
pf2 = 0.8;
sf2 = 0.9;
pb = linspace(pf1,pf2,1e3)*pi;

bp = designfilt(‘bandpassfir’, .
‘StopbandAttenuation1’,40, ‘StopbandFrequency1’,sf1.
‘PassbandFrequency1′,pf1,’PassbandRipple’,3,’PassbandFrequency2′,pf2, .
‘StopbandFrequency2′,sf2,’StopbandAttenuation2’,30);

[h,w] = freqz(bp,1024);
hpb = freqz(bp,pb);

subplot(2,1,2)
plot(w/pi,db(h),pb/pi,db(hpb),’.-‘)
axis([0 1 -60 10])
xlabel(‘Normalized Frequency (\times\pi rad/sample)’)
ylabel(‘Magnitude (dB)’)

freqz(___) with no output arguments plots the frequency response of the filter.

Frequency Response of an FIR filter

Design an FIR lowpass filter of order 80 using a Kaiser window with . Specify a normalized cutoff frequency of rad/sample. Display the magnitude and phase responses of the filter.

b = fir1(80,0.5,kaiser(81,8));
freqz(b,1)

Design the same filter using designfilt. Display its magnitude and phase responses using fvtool.
d = designfilt(‘lowpassfir’,’FilterOrder’,80, .
‘CutoffFrequency’,0.5,’Window’,);
freqz(d)

Note: If the input to freqz is single precision, the frequency response is calculated using single-precision arithmetic. The output, h , is single precision.

[ h , w ] = freqz( sos , n ) returns the n -point complex frequency response corresponding to the second-order sections matrix, sos .

[ h , f ] = freqz(___, n , fs ) returns the frequency response vector, h , and the corresponding physical frequency vector, f , for the digital filter with numerator and denominator polynomial coefficients stored in b and a , respectively, given the sample rate, fs .

[ h , f ] = freqz(___, n ,’whole’, fs ) returns the frequency at n points ranging between 0 and fs .

h = freqz(___, w ) returns the frequency response vector, h , at the normalized frequencies supplied in w .

h = freqz(___, f , fs ) returns the frequency response vector, h , at the physical frequencies supplied in f .

How to use `feedback` function in Matlab?

Matlab’s feedback function is used to obtain the closed loop transfer function of a system. Example:

enter image description here

sys = feedback(sys1,sys2) returns a model object sys for the negative feedback interconnection of model objects sys1 , sys2 . To compute the closed-loop system with positive feedback, use sign = +1, for negative feedback we use -1.

My question arises when we have a system of the following type:

enter image description here

According to these docs, we can use feedback to create the negative feedback loop with G and C.

This is a source of confusion, shouldn’t the above be: sys = feedback(G*C,1,-1)? These are not the same.

However, looking at these docs, for a unit loop gain k, you can compute the closed-loop transfer function T using:

enter image description here

Why are we using 1 and not -1 ? This is still negative feedback and not positive feedback.

Какие функции реализуют операторы freqs feedback

Frequency response of digital filter

Syntax

Description

[ h , w ] = freqz( b,a , n ) returns the n -point frequency response vector, h , and the corresponding angular frequency vector, w , for the digital filter with numerator and denominator polynomial coefficients stored in b and a , respectively.

[ h , w ] = freqz(___, n ,’whole’) returns the frequency response at n sample points around the entire unit circle.

Frequency Response from Transfer Function

Compute and display the magnitude response of the third-order IIR lowpass filter described by the following transfer function:

Express the numerator and denominator as polynomial convolutions. Find the frequency response at 2001 points spanning the complete unit circle.

[ h , w ] = freqz( d , n ) returns the n -point complex frequency response for the digital filter, d .

Frequency Response of an FIR Bandpass Filter

Design an FIR bandpass filter with passband between and rad/sample and 3 dB of ripple. The first stopband goes from 0 to rad/sample and has an attenuation of 40 dB. The second stopband goes from rad/sample to the Nyquist frequency and has an attenuation of 30 dB. Compute the frequency response. Plot its magnitude in both linear units and decibels. Highlight the passband.
sf1 = 0.1;
pf1 = 0.35;
pf2 = 0.8;
sf2 = 0.9;
pb = linspace(pf1,pf2,1e3)*pi;

bp = designfilt(‘bandpassfir’, .
‘StopbandAttenuation1’,40, ‘StopbandFrequency1’,sf1.
‘PassbandFrequency1′,pf1,’PassbandRipple’,3,’PassbandFrequency2′,pf2, .
‘StopbandFrequency2′,sf2,’StopbandAttenuation2’,30);

[h,w] = freqz(bp,1024);
hpb = freqz(bp,pb);

subplot(2,1,2)
plot(w/pi,db(h),pb/pi,db(hpb),’.-‘)
axis([0 1 -60 10])
xlabel(‘Normalized Frequency (\times\pi rad/sample)’)
ylabel(‘Magnitude (dB)’)

freqz(___) with no output arguments plots the frequency response of the filter.

Frequency Response of an FIR filter

Design an FIR lowpass filter of order 80 using a Kaiser window with . Specify a normalized cutoff frequency of rad/sample. Display the magnitude and phase responses of the filter.

b = fir1(80,0.5,kaiser(81,8));
freqz(b,1)

Design the same filter using designfilt. Display its magnitude and phase responses using fvtool.
d = designfilt(‘lowpassfir’,’FilterOrder’,80, .
‘CutoffFrequency’,0.5,’Window’,);
freqz(d)

Note: If the input to freqz is single precision, the frequency response is calculated using single-precision arithmetic. The output, h , is single precision.

[ h , w ] = freqz( sos , n ) returns the n -point complex frequency response corresponding to the second-order sections matrix, sos .

[ h , f ] = freqz(___, n , fs ) returns the frequency response vector, h , and the corresponding physical frequency vector, f , for the digital filter with numerator and denominator polynomial coefficients stored in b and a , respectively, given the sample rate, fs .

[ h , f ] = freqz(___, n ,’whole’, fs ) returns the frequency at n points ranging between 0 and fs .

h = freqz(___, w ) returns the frequency response vector, h , at the normalized frequencies supplied in w .

h = freqz(___, f , fs ) returns the frequency response vector, h , at the physical frequencies supplied in f .

Проектирование цифровых фильтров в MATLAB с использованием возможностей пакета Signal Processing Toolbox

При расчете используются нормированные значения частот, измеряемые в радианах на отсчет (при такой нормировке частота дискретизации равна , а частота Найквиста — ). По умолчанию выбирается 512 частотных точек, равномерно распределенных в диапазоне .

Чтобы задать количество частотных точек для расчета, используется третий входной параметр n (частоты при этом по прежнему равномерно распределяются в диапазоне ):

Чтобы перейти от использования нормированных частот к использованию абсолютных значений частот в Гц, используется четвертый входной параметр Fs, равный частоте дискретизации (частоты при этом равномерно распределяются в диапазоне ):

Можно заставить функцию freqz использовать ряд частот, равномерно распределенных на интервале вплоть до частоты дискретизации. Это является необходимым при анализе фильтров с комплексными коэффициентами, частотные характеристики которых не являются симметричными относительно частоты Найквиста. Такое указание дается функции freqz с помощью четвертого входного параметра – строки ‘whole’:

Параметр Wn задает частоту среза ФНЧ, если это скаляр. Следует помнить, что при обращении к указанным функциям при проектировании цифровых фильтров частота среза Wn задается в единицах нормированной частоты в диапазоне от 0 до 1, где 1 соответствует половине частоты дискретизации или частоте Найквиста. Частота среза Wn соответсвует значению амплитуды, равному . Если его задать как двухкомпонентный вектор Wn=[w1,w2], то функция будет возвращать характеристики полосового фильтра. При отсутствии параметра ’ftype’ получаются характеристики ФНЧ или полосового фильтра. Параметр ’ftype’ имеет два значения, что позволяет проектировать еще два важных типа фильтров: high (ФВЧ), stop (режекторный с заданием Wn=[w1,w2]).

b = 0.0642 0.3009 0.5436 0.4514 0.1407 -0.0156 -0.0097 0.0021

a = 1.0000 0.0000 0.4776

Функция yulewalk служит для проектирования рекурсивного цифрового фильтра Юла-Уокера порядка n с заданной АЧХ, которая представляется векторами частот f и значений m. Частоты должны быть заданы в интервале , где 1 соответствует частоте Найквиста (частота, равная половине частоты дискретизации). Вектор частот должен иметь первый элемент 0 и последний 1, а в промежутке частоты указываются в возрастающем порядке. Если надо задать скачок АЧХ, то частота скачка указывается подряд дважды, а в векторе m указываются значения АЧХ до скачка и после скачка.

Величина Wp нормирована и должна находиться в диапазоне , где 1 соответсвует частоте Найквиста или половине частоты дискретизации [2]. Величина Ws находится в том же диапазоне, что и Wp. Кроме минимального порядка также вычисляется частота среза Wn, которая далее может быть использована в качестве исходной величины для расчета параметров фильтров.

,

.

В простейшей форме b=fircls1(n,W0,dp,ds) функция создает вектор коэффициентов ФНЧ порядка n с частотой среза W0 между 0 и 1, где 1 соответствует половине частоты дискретизации, максимально допустимой функцией ошибки АЧХ в полосе пропускания dp и максимальной функцией ошибки в полосе задержания ds. Параметр ‘high’ задает проектирование ФВЧ. Задается дополнительный параметр wt, выше которого или ниже которого выполняются требования к АЧХ проектируемого фильтра. Если wt в полосе пропускания, то , где — функция ошибки. Если wt вне полосы, то пропускания . Векторы up и lo имеют то же число элементов, что и вектор amp, и задают верхние и нижние границы ЧХ для каждой из полос фильтра.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *