[Beginner] Problem of :Vectors must be the same lengths
7 views (last 30 days)
Show older comments
Will Hai
on 25 Sep 2017
Commented: Cam Salzberger
on 3 Oct 2017
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
on 25 Sep 2017
Please post the complete error message in every case.
What is the purpose of 0:NaN:0?
Accepted Answer
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
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
More Answers (0)
See Also
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!