" Array indices must be positive integers or logical values." appearing with piecewise function

Working on a function that takes a vector input and runs it through a piecewise and returns a vector of output values, getting this error when running it.
for i = 0:length(x)
if x(i)<0
y(i) = sind(x(i));
elseif 0<=x(i) && x(i)<=1
y(i)=x(i).^(1/2);
elseif 1<x(i) && x(i)<x(6)
y(i) = 1./factorial(floor(x(i)));
elseif x(i)>=6
y(i) = 200*log(x(i));
end
end

1 Comment

The problem is on this line:
for i = 0:length(x)
Like is standard in mathematics, indexing starts with one.

Sign in to comment.

 Accepted Answer

x=rand(1,7) %this is vector input , an example
for i = 1:length(x)
if x(i)<0
y(i) = sind(x(i));
elseif 0<=x(i) && x(i)<=1
y(i)=x(i).^(1/2);
elseif 1<x(i) && x(i)<x(6)
y(i) = 1./factorial(floor(x(i)));
elseif x(i)>=6
y(i) = 200*log(x(i));
end
end
y

More Answers (0)

Categories

Find more on Debugging and Improving Code in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!