我是MATLAB的新手,我有以下代码:
a=500;
PI=3.14159265;
radconvert=PI/180;
degconvert=180/PI;
% values at t=9, t=10 and t=11 respectively
alpha=[54.80 54.06 53.34];
beta=[65.59 64.59 63.62];
% converting degrees to radians
for i = 1:3
alpha(i) = alpha(i)*radconvert;
end
for i = 1:3
beta(i) = beta(i)*radconvert;
end
% declaring x and y functions
function x(a, alpha, beta)
(a*tan(beta))/(tan(beta)-tan(alpha));
function y(a, alpha, beta)
(a*tan(alpha)*tan(beta))/(tan(beta)-tan(alpha));
% doing the calculations
vx1=x(a, alpha(2), beta(2)) - x(a, alpha(1), beta(1));
vy1=y(a, alpha(2), beta(2)) - y(a, alpha(1), beta(1));
vf1=sqrt(vx1^2 + vy1^2);
vx2=x(a, alpha(3), beta(3)) - x(a, alpha(2), beta(2));
vy2=y(a, alpha(3), beta(3)) - y(a, alpha(2), beta(2));
vf2=sqrt(vx2^2 + vy2^2);
vf=(vf1+vf2)/2;
vxavg=(vx1+vx2)/2;
vyavg=(vy1+vy2)/2;
theta = atan(vyavg/vxavg)*degconvert;
% printing the values
sprintf('Velocity at t=10 is: %.2f\n', vf);
sprintf('Climb angle theta is: %.2f\n', theta);
如果我尝试运行它,我会收到以下错误消息:
???错误:文件:code.m行:20列:1函数定义是 在这种情况下不允许。
我想我不能在同一个.m文件中声明和使用函数。有人可以帮我解决这个问题吗?
答案 0 :(得分:4)
不允许在脚本中定义函数。这是两件不同的事情。您的.m文件是脚本的函数。但可以在MATLAB脚本中定义anonymous functions。由于我不会在这里扩展的范围问题,您的函数参数不应该与主脚本中的变量具有相同的名称。它们的范围相交。如果前一句没有意义,只需确保您的参数名称与您在脚本中调用的内容不同。具有无限功能的代码应如下所示:
a=500;
PI=3.14159265;
radconvert=PI/180;
degconvert=180/PI;
% values at t=9, t=10 and t=11 respectively
alpha=[54.80 54.06 53.34];
beta=[65.59 64.59 63.62];
% converting degrees to radians
for i = 1:3
alpha(i) = alpha(i)*radconvert;
end
for i = 1:3
beta(i) = beta(i)*radconvert;
end
% declaring ananymous x and y functions
x = @(mA, mAlpha, mBeta) ...
(mA*tan(mBeta))/(tan(mBeta)-tan(mAlpha));
y = @(mA, mAlpha, mBeta) ...
(mA*tan(mAlpha)*tan(mBeta))/(tan(mBeta)-tan(mAlpha));
% doing the calculations
vx1=x(a, alpha(2), beta(2)) - x(a, alpha(1), beta(1));
vy1=y(a, alpha(2), beta(2)) - y(a, alpha(1), beta(1));
vf1=sqrt(vx1^2 + vy1^2);
vx2=x(a, alpha(3), beta(3)) - x(a, alpha(2), beta(2));
vy2=y(a, alpha(3), beta(3)) - y(a, alpha(2), beta(2));
vf2=sqrt(vx2^2 + vy2^2);
vf=(vf1+vf2)/2;
vxavg=(vx1+vx2)/2;
vyavg=(vy1+vy2)/2;
theta = atan(vyavg/vxavg)*degconvert;
% printing the values
msg = sprintf('Velocity at t=10 is: %.2f\n', vf);
disp(msg);
msg = sprintf('Climb angle theta is: %.2f\n', theta);
disp(msg);
我最后还修改了你的打印。