Plot inside a function

조회 수: 26 (최근 30일)
Oskar Mevik Päts
Oskar Mevik Päts 2019년 11월 12일
댓글: Oskar Mevik Päts 2019년 11월 14일
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
Oskar Mevik Päts
Oskar Mevik Päts 2019년 11월 14일
Muchos gracias!

댓글을 달려면 로그인하십시오.

추가 답변 (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