## Plot inside a function

### Oskar Mevik Päts (view profile)

on 12 Nov 2019 at 17:24
Latest activity Commented on by Oskar Mevik Päts

### Oskar Mevik Päts (view profile)

on 14 Nov 2019 at 9:36

### Jess Lovering (view profile)

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!

### Jess Lovering (view profile)

on 12 Nov 2019 at 17:30

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

on 12 Nov 2019 at 17:40
@ Oskar Mevik Päts, note that these types of problems that Jess Lovering identified can often be avoided by using proper indentation.
To smart-indent your code, from the editor, select all of your code (ctrl + a) and then smart-indent (ctrl+i).
On another note, here's a cleaner and faster version of your function.
function y = jff(x)
d = 75;
a = 1 / 3;
y = nan(size(x));
y(x <= 0) = 0;
y(x > 0 & x <= d) = a .* x(x > 0 & x <= d);
y(x > d) = a .* d;
end
But if you insist on using the slower loop method, at least pre-allocate your loop variable and follow these other suggestions:
function y = fp(x) %remove ;
d = 75;
a = 1 / 3;
y = nan(size(x)); % pre-allocate your loop var!
for i = 1: numel(x) %use numel instead of length() & remove ;
if x(i) <= 0 %remove ;
y(i) = 0;
elseif x(i) > 0 & x(i) <= d %remove ;
y(i) = a .* x(i);
elseif x(i) > d %remove ;
y(i) = a .* d;
end
end
plot(x,y)
end
Oskar Mevik Päts

### Oskar Mevik Päts (view profile)

on 14 Nov 2019 at 9:36
Muchos gracias!