mardi 6 novembre 2018

Function returns wrong data if fed a list of numbers as opposed to a single number

I am having a bit of trouble with getting correct output from my function when I plot it.

I have written a simple function that takes x as input and just returns x as output. But if x is greater than 75 I return 25 as an output instead (essentially capping the output to 25 if x exceeds 75).

The function works as intended when I feed it a normal number, but when I give it a list of numbers it completely ignores my if-statement and returns just x regardless of what the input is.

Full code:

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

My plot ends up looking like this: enter image description here But I am I expecting for my plot to look something like this: enter image description here

However if I just use the function with a single number it works as intended. For example if I did something like this instead:

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

Why does my function not work with an array input? How do I fix it?

Aucun commentaire:

Enregistrer un commentaire