Plot inside a function

14 Ansichten (letzte 30 Tage)
Oskar Mevik Päts
Oskar Mevik Päts am 12 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!

Akzeptierte Antwort

Jess Lovering
Jess Lovering am 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 Kommentare
Adam Danz
Adam Danz am 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 am 14 Nov. 2019
Muchos gracias!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Large Files and Big Data finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by