这是 Matlab 函数调用中的错误吗?
Is this a bug in Matlab function call?
我在这里使用的代码是为了说明可能的错误。在代码中我定义了如下三个函数并尝试将它们可视化。
第一个:
$$y_1(x)=5\sin(x)$$
第二个:
$$y_2(x)=12-8\cos(x)$$
第三个是上面两个的分段组合:
when x<0:
$$y_3(x)=y_1(x)$$
when x>=0:
$$y_3(x)=(y_1(x)+y_2(x))/2$$
当我在Matlab中运行如下代码时,保存为m2mPlot.m
:
function m2mPlot
clear all
close all
clc
global a b c;
a=12;
b=8;
c=5;
t=-pi:.1:pi;
plot(t,y1(t),'b')
hold on
plot(t,y2(t),'m')
plot(t,y3(t),'r')
legend('y1','y2','y3')
function y=y1(t)
% The first function for testing
global c;
y=c*sin(t);
function y=y2(t)
% The 2nd function for testing
global a b;
y=a-b*cos(t);
function y=y3(t)
% The 3rd function for testing
if t<0 % It seems this logic value is always FALSE, why?
y=y1(t);
else
y=(y2(t)+y1(t))/2;
end
我得到了:
这表明在第三个子函数中,逻辑表达式:t<0 始终为 FALSE,无论 t 的实际值是多少。
这是 Matlab 中的错误吗?如何避免这样的问题?
这不是 MATLAB 中的错误,您只是使用不当。
您正在调用 y3(t)
,其中 t
是一个向量,即 t=-pi:.1:pi;
。但是 y3
的代码在条件中使用了 t
,即 if t<0
。由于 t<0
的结果是一个向量,而 if
语句需要一个标量,因此它不会像您预期的那样工作。正如 Troy Haskin 在评论中指出的那样,来自 MATLAB docs:
if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric).
Otherwise, the expression is false.
您的 t<0
向量包含许多 false
个值,因此 if
将其计算为 false
。我建议你只给 MATLAB if
一个标量。
如果您想以矢量化方式创建 y3
函数,请尝试以下方法:
function y=y3(t)
y=y1(t).*(t<0) + y2(t).*(t>=0);
end
我在这里使用的代码是为了说明可能的错误。在代码中我定义了如下三个函数并尝试将它们可视化。
第一个:
$$y_1(x)=5\sin(x)$$
第二个:
$$y_2(x)=12-8\cos(x)$$
第三个是上面两个的分段组合:
when x<0:
$$y_3(x)=y_1(x)$$
when x>=0:
$$y_3(x)=(y_1(x)+y_2(x))/2$$
当我在Matlab中运行如下代码时,保存为m2mPlot.m
:
function m2mPlot
clear all
close all
clc
global a b c;
a=12;
b=8;
c=5;
t=-pi:.1:pi;
plot(t,y1(t),'b')
hold on
plot(t,y2(t),'m')
plot(t,y3(t),'r')
legend('y1','y2','y3')
function y=y1(t)
% The first function for testing
global c;
y=c*sin(t);
function y=y2(t)
% The 2nd function for testing
global a b;
y=a-b*cos(t);
function y=y3(t)
% The 3rd function for testing
if t<0 % It seems this logic value is always FALSE, why?
y=y1(t);
else
y=(y2(t)+y1(t))/2;
end
我得到了:
这是 Matlab 中的错误吗?如何避免这样的问题?
这不是 MATLAB 中的错误,您只是使用不当。
您正在调用 y3(t)
,其中 t
是一个向量,即 t=-pi:.1:pi;
。但是 y3
的代码在条件中使用了 t
,即 if t<0
。由于 t<0
的结果是一个向量,而 if
语句需要一个标量,因此它不会像您预期的那样工作。正如 Troy Haskin 在评论中指出的那样,来自 MATLAB docs:
if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false.
您的 t<0
向量包含许多 false
个值,因此 if
将其计算为 false
。我建议你只给 MATLAB if
一个标量。
如果您想以矢量化方式创建 y3
函数,请尝试以下方法:
function y=y3(t)
y=y1(t).*(t<0) + y2(t).*(t>=0);
end