Array indices must be positive integers or logical values.

clc;
x = -6; %input value for following expression
if x < -5
f(x) = 0;
elseif -5 <= x && x < 5;
f(x) = 2 * x^1/2 + exp(x/4);
elseif 5 <= x && x <= 20;
f(x) = log((x^2));
else
f(x) = 0;
end
f(x)
how can i get my code to work for values -infinity to 0 for this expression? i keep getting this error code
Array indices must be positive integers or logical values.
Error in Homework_two (line 11)
f(x) = 0;

 Accepted Answer

f is interpreted here as an array, and arrays can only be indexed with positive integers or logical values.
So f(-6) is forbidden.
You can use
x = -6:0.1:10 ; %input value for following expression
f = zeros(size(x));
f(-5 <= x & x < 5) = 2 * sqrt(x(-5 <= x & x < 5)) + exp(x(-5 <= x & x < 5)/4);
f(5 <= x & x <= 20) = log(x(5 <= x & x <= 20).^2);
plot(x,f)
Warning: Imaginary parts of complex X and/or Y arguments ignored.
But note that x^(1/2) gives imaginary results for x < 0.

1 Comment

Yah that makes sense, Thank you for clarifying that for me.

Sign in to comment.

More Answers (1)

x = -6; %input value for following expression
if x < -5
f(x) = 0;
There's no such thing as element -6 of an array in MATLAB. If you want f to be one element long and you want its value to depend on x, assign to f not f(x).

Asked:

on 5 Nov 2022

Commented:

on 5 Nov 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!