MATLAB: I keep getting Array indices must be positive integers or logical values.

function

i keep getting Array indices must be positive integers or logical values and i have no idea how to slove this. i even trying looping it
x = linspace(-3,5,100)'
plot(x,mywierdfcn(x))
function f = mywierdfcn (x)
if x > 2
f(x) =x.^2;
else x <= 2
f(x) = 2*x;
end

Best Answer

Jithin - from
x = linspace(-3,5,100)
x is an array of negative and positives real numbers in the interval [-3,5]...so only a handful of the 100 numbers might be positive integers. You are then using each of these values as an index into an array
plot(x,mywierdfcn(x))
where
function f = mywierdfcn (x)
if x > 2
f(x) =x.^2;
else x <= 2
f(x) = 2*x;
end
and so the error message makes sense - non-positive integers cannot be used as indices into an array. You can rewrite your function as
function f = mywierdfcn (x)
f = x;
f(x > 2) = x(x > 2).^2;
f(x <= 2) = x(x <= 2).*2;
We can do this since (for example) x > 2 will return a logical array of zeros and ones where a one corresponds to an index in x where x(index) is greater than 2. See the section Logical Indexing from https://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html for details.