0

我对 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 文件中声明和使用函数。有人可以帮我解决这个问题吗?

4

1 回答 1

4

不允许在脚本中定义函数。这是两个不同的东西。您的 .m 文件是脚本的函数。但是,您可以在 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 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);

最后我还修复了你的打印。

于 2013-04-15T23:33:20.763 回答