【问题标题】:Function returns wrong data if fed a list of numbers as opposed to a single number如果输入数字列表而不是单个数字,则函数返回错误数据
【发布时间】:2018-11-06 19:08:37
【问题描述】:

在绘制函数时,我无法从函数中获取正确的输出。

我编写了一个简单的函数,它以x 作为输入,只返回x 作为输出。但如果x 大于75,我会返回25 作为输出(如果x 超过75,则基本上将输出限制为25)。

当我给它一个普通数字时,该函数按预期工作,但是当我给它一个数字列表时,它完全忽略了我的 if 语句并只返回 x 而不管输入是什么。

完整代码:

x = 0:0.1:200;
y = f(x);
plot(x,y)
function output = f(x)
    if (x >= 75)
        output = 25;
    else
        output = x;
    end
end

我的情节最终看起来像这样: 但我希望我的情节看起来像这样:

但是,如果我只使用带有单个数字的函数,它会按预期工作。例如,如果我改为这样做:

x = 75;
y = f(x)
function output = f(x)
    if (x >= 75)
        output = 25;
    else
        output = x;
    end
end

为什么我的函数不适用于数组输入?我该如何解决?

【问题讨论】:

  • 不在 Suever 的回答中:if 只有在数组中的所有元素都为真时才会触发数组。因此,如果x 中的任何元素不是>=75,则执行else 语句。 if x>=75 等价于 if all(x>=75)
  • 另外,一个班轮output = (x>75).*25 + (x<=75).*x; 工作。逻辑数组(x>75)(x<=75) 用作掩码来选择是选择25 还是选择来自x 的值。它受益于 Matlab 在矢量化操作上的性能(或者更确切地说,在运行 for 循环时不会受到 Matlab 缺乏性能的影响)。使用以下语法使其成为函数句柄:output_fcn = @(x) (x>75).*25 + (x<=75).*x; plot(x,output_fcn(x));

标签: matlab function if-statement plot


【解决方案1】:

如果您希望您的函数对数组进行操作,您需要显式更改它以使用数组,或者为每个元素调用您的函数。

为每个元素调用

x = [1, 2, 100];

% Calls the function f for each element in x
output = arrayfun(@f, x);
% [1, 2, 25]

编写f 来处理数组

为此,您可以使用 logical indexing 将数组中值大于或等于 75 的元素替换为 25。这将是性能最高的选项

function x = f(x)
    % Creates a logical index using `x >= 75` and assigns the value `25`
    % to those elements matching that criteria
    x(x >= 75) = 25;
end

x = [1, 2, 100];
f(x)
% [1, 2, 25]

或者你可以编写你的函数来循环输入数组

function output = f(x)
    output = x
    for k = 1:numel(x)
        if output(k) >= 75
            output(k) = 25
        end
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多