Plot inside a function

11 次查看(过去 30 天)
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
Jess Lovering 2019-11-12
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 个评论
Adam Danz
Adam Danz 2019-11-12
@ 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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by