MATLAB 中的分段函数

Piecewise functions in MATLAB

我今年才开始使用 MATLAB for Uni,作为家庭作业测验问题,我被要求创建一个分段函数(我称之为 "piecewise_method"),它能够执行不同的"x" 上的等式取决于 "x" 是否低于 0、介于 0 和 8 之间或高于 8。这是我到目前为止编写的代码。

function solution = piecewise_method(x)

% given the value of the input x, the function
% piecewise_method will choose from one of the three specified
% equations to enact upon the given value of x
% and give the user a solution

solution = zeros(size(x));
e = exp(1);

for j = 1:size(x)
    a = x(j);

    if a < 0
        solution(j) = -a.^3 - 2*a.^2 + 3*a;
    elseif (a >= 0) && (a <= 8)
        solution(j) = (12/pi)*sin(pi*a./4);
    else
        solution(j) = ((600.*e.^(a-8))./(7*(14+6.*e.^(a-8))) - 30/7);
    end
end

当运行输入...

x = -3:12

它为变量解产生这个结果...

解决方案=

 0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0

现在,这向我表明数组已正确创建,但出于某种原因,for 循环未正确 运行ning,或未按预期进行。我尝试从基础级别开始多次重建 for 循环,但是当我开始输入方程式时它又开始崩溃,所以我相信我的方程式可能有问题(这就是为什么我在各处都加上括号,以防万一)。

题中还要求我使用if语句,所以无法尝试使用其他方法来产生分段法函数,而且我四处寻找,if语句的例子似乎并不多分段函数。

如果您能提供任何可以帮助我使用此功能的建议,将不胜感激,谢谢!

P.S。如果您有任何建议可以改进我的问题,那也很好!

您应该在 for 循环中使用 length 而不是 size

size 函数的输出是 x 的维度,对于您的 x=-3:12 returns size(x)=[1 16] 示例。那么你的 for 循环将 运行 for j=1:size(x),即 j=1:1,即 j=1.

length 的输出是 x 的最大数组维度的长度,如 here 所列。在您的示例中:length(x) = 16,然后是 j=1:length(x)=1:16

或者,您可以使用 size(x,2),这将 return x 的第二个维度的大小,与本例中的 length 相同。

如评论和 中所述,您需要检查循环。我会使用 size(x,2)x 中的列数)或 numel(x)x 中的元素数)。

for j = 1:numel(x)
    % ...

别人推荐length(x)也就是max(size(x))。我通常会尽量避免这种情况,因为它不明确您要查找矩阵的哪个维度。

除了只是重复信息之外,我想向您展示可以使用逻辑索引更有效地执行此操作,并完全删除有问题的循环...

function solution = piecewise_method(x)

% given the value of the input x, the function
% piecewise_method will choose from one of the three specified
% equations to enact upon the given value of x
% and give the user a solution

solution = zeros(size(x));
e = exp(1);

idx = (x<0);
solution(idx) = -x(idx).^3 - 2*x(idx).^2 + 3*x(idx);
idx = (x>=0 & x<=8);
solution(idx) = (12/pi)*sin(pi*x(idx)/4);
idx = (x>8);
solution(idx) = (600*e.^(x(idx)-8))./(7*(14+6*e.^(x(idx)-8))) - 30/7;

请注意,您可以轻松地在数组中设置条件和(匿名)函数并循环它们以使其更加灵活。