MATLAB: Plot inside a function

beginnerplot

Hi,
I want to plot Distance (x) vs. Velocity (y).
With my code
function y = fp(x);
d = 75;
a = 1 / 3;
for i = 1: length(x);
if x(i) <= 0;
y(i) = 0;
elseif x(i) > 0 & x(i) <= d;
y(i) = a .* x(i);
elseif x(i) > d;
y(i) = a .* d;
end
end
I execute for example
x = [0:1:100];
plot(x,fp(x))
and it works. But what I want is to just execute fp(x) and get the plot from the function,
but I get the error "Vectors must of same length" with the code
function y = fp(x);
d = 75;
a = 1 / 3;
for i = 1: length(x);
if x(i) <= 0;
y(i) = 0;
elseif x(i) > 0 & x(i) <= d;
y(i) = a .* x(i);
elseif x(i) > d;
y(i) = a .* d;
end
plot(x,y)
end
Whats the deal? Thanks!

Best Answer

In the code it looks like you have the plot within your for loop. You need an additional end before the plot line. Does that fix your issue?
function y = fp(x);
d = 75;
a = 1 / 3;
for i = 1: length(x);
if x(i) <= 0;
y(i) = 0;
elseif x(i) > 0 & x(i) <= d;
y(i) = a .* x(i);
elseif x(i) > d;
y(i) = a .* d;
end
end
plot(x,y)
end