[Beginner] Problem of :Vectors must be the same lengths

7 views (last 30 days)
This is a Matlab beginner from Hong Kong.
I was trying to plot a graph with step function but it seems that there was something wrong with my code.
I have no idea of the error: vectors must be the same lengths plot.
The following is my code:
function practice2
to = -1:0.2:0;
t1 = 0:0.2:1;
t2 = 1:0.2:2;
t3 = 2:0.2:3;
t4 = 3:0.2:4;
yo = 0:NaN:0;
y1 = 2*t1;
y2 = -(2*t3) + 6;
t = [to t1 t2 t3 t4];
y = [yo y1 yo y2 yo];
plot (t,y)
  1 Comment
Jan
Jan on 25 Sep 2017
Please post the complete error message in every case.
What is the purpose of 0:NaN:0?

Sign in to comment.

Accepted Answer

Cam Salzberger
Cam Salzberger on 25 Sep 2017
Edited: Cam Salzberger on 25 Sep 2017
Hello Will,
If you take a look at the variables that are produced when you run the code, you might notice that yo is not a length-6 vector with all 0s, but instead a scalar NaN. What I think you meant to use instead was:
yo = zeros(size(to));
Also note that you are repeating the points at 0, 1, 2, and 3, since they are each contained in both the proceeding and subsequent "t" vectors.
I'd recommend just creating your "t" vector in one go, creating your "y" vector as all zeros, and then using logical indexing to modify the parts of the "y" vector that should be non-zero.
-Cam
  2 Comments
Will Hai
Will Hai on 29 Sep 2017
I know the problem of repeating the points, however i don't get the idea of using logical indexing in my situation after i read through the hyperlink
it will be good if i can have more explanation from you
Thanks for your suggestion
Cam Salzberger
Cam Salzberger on 3 Oct 2017
Well, you can make a single "t" and "y" vector with something like:
t = -1:0.2:4;
y = zeros(size(t));
Then you can only change the values of particular parts of the "y" vector, based on the values of "t":
y(t >= 0 & t < 1) = 2*t(t >= 0 & t < 1);
y(t >= 2 & t < 3) = 6-2*t(t >= 2 & t < 3);
This avoids the repeated points and cleans up the code a little, though it may be very slightly less time-efficient.
-Cam

Sign in to comment.

More Answers (0)

Categories

Find more on Line 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!