如何在MATLAB中将此代码转换为函数,以便我可以通过调用它来使用它
%Lathi MS2P4 pg 232从信号和系统中稍微修改的代码 如何使此代码成为函数?这样我就可以“调用”它来使用它。而不是一次又一次地粘贴整个东西。这只是两个函数的卷积动画如何在MATLAB中将此代码转换为函数,以便我可以通过调用它来使用它,matlab,Matlab,%Lathi MS2P4 pg 232从信号和系统中稍微修改的代码 如何使此代码成为函数?这样我就可以“调用”它来使用它。而不是一次又一次地粘贴整个东西。这只是两个函数的卷积动画 figure(1) % Create figure window and make visible on screen x = @(t) cos(2*pi*3*t).* u(t); h = @(t) u(t)-u(t-1); dtau = 0.005; tau = -1:dtau:4; ti = 0; tvec =
figure(1) % Create figure window and make visible on screen
x = @(t) cos(2*pi*3*t).* u(t);
h = @(t) u(t)-u(t-1);
dtau = 0.005;
tau = -1:dtau:4;
ti = 0;
tvec = -1:0.1:5;
y = NaN*zeros(1,length(tvec)); % Pre-allocate memory
for t = tvec,
ti = ti + 1; % Time index
xh = x(t-tau).*h(tau);
lxh = length(xh);
y(ti) = sum(xh.*dtau); % Trapezoidal approximation of integral
subplot(2,1,1)
plot(tau,h(tau),'k-',tau,x(t-tau),'k--',t,0,'ok')
axis([tau(1) tau(end) -2.0 2.5])
patch([tau(1:end-1);tau(1:end-1);tau(2:end);tau(2:end)],...
[zeros(1,lxh-1);xh(1:end-1);xh(2:end);zeros(1,lxh-1)],...
[0.8 0.8 0.8],'edgecolor','none')
xlabel('\tau')
legend('h(\tau)','x(t-\tau)','t','h(\tau)x(t-\tau)')
c = get(gca,'children');
set(gca,'children',[c(2);c(3);c(4);c(1)]);
subplot(2,1,2)
plot(tvec,y,'k',tvec(ti),y(ti),'ok')
xlabel('t')
ylabel('y(t) = \int h(\tau)x(t-\tau) d\tau')
axis([tau(1) tau(end) -1.0 2.0])
grid
drawnow
% pause
end
您可以使用Matlab的
函数
,如下所述
因此,您必须在顶部写上“function yourFunctionName”,然后您可以使用它的名称来调用它,在这种情况下,
yourFunctionName
。以下是使用您的精确代码的方法,一个简单的函数定义,并添加了OP中缺少的u(t)
:
figure(1) % figure window outside function
u = @(t)heaviside(t); % define step function
x = @(t) cos(2*pi*3*t).* u(t);
h = @(t) u(t)-u(t-1);
dtau = 0.005;
convol_anime(x, h, dtau); % pass function handles + parameters
您已经定义了:
function convol_anime(x, h, dtau)
tau = -1:dtau:4; ti = 0; tvec = -1:0.1:5;
y = nan*zeros(1,length(tvec));
...
函数护航动画(x,h)。我用它来创建我的函数。当我放入两个任意函数x(t)和h(t)(如上所述)时,动画图不会显示。怎么会?我把它叫做conval_anime(x(t),h(t)),因为上面的x(t)和h(t)是通过去掉(t)得到的,所以只需输入x,y