Plot inside a function

27 views (last 30 days)
Oskar Mevik Päts
Oskar Mevik Päts on 12 Nov 2019
Commented: Oskar Mevik Päts on 14 Nov 2019
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!

Accepted Answer

Jess Lovering
Jess Lovering on 12 Nov 2019
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
  2 Comments
Adam Danz
Adam Danz on 12 Nov 2019
@ 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 on 14 Nov 2019
Muchos gracias!

Sign in to comment.

More Answers (0)

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!