How to plot different length of vectors?

9 views (last 30 days)
Zin Ko Khaing
Zin Ko Khaing on 6 May 2019
Edited: Adam Danz on 6 May 2019
for k=1:3000
xvalue1(k)=k;
end
for k=1:2999
xvalue(k)=k;
end
figure;
d5=X_est(5,:);
plot(xvalue,d5);
hold on,
plot(wr);
legend('estimated value','actual value');
  5 Comments
dpb
dpb on 6 May 2019
"2:3000" is a vector index expression of 3000-2+1-->2999 elements which is one off 3000...
The language is a barrier here...
Zin Ko, simply write
wr(2:3000)
to reference the elements other than the first.
If you want to eliminate that first element entirely, then just overwrite wr
wr=wr(2:3000);
More generically and better practice to not bury "magic numbers" in code would be
wr=wr(2:end)
Adam Danz
Adam Danz on 6 May 2019
Edited: Adam Danz on 6 May 2019
I see. So, in this line
plot(xvalue,d5);
xvalue is a vector of length 3000 and d5 is a vector of length 2999.
Assuming there's a correspondance between these variables except for the first or last value, you can just trim the extra values. This often happens when differentiating, for example.
plot(xvalue(2:end), d5)
% or
plot(xvalue(1:end-1), d5)
These will "work" (they won't cause an error) but it's up to you to make sure they conceptually work.

Sign in to comment.

Answers (1)

dpb
dpb on 6 May 2019
for k=1:3000
xvalue1(k)=k;
end
MATLAB is MATrix LABoratory -- use vector facilities...
xvalue1=1:3000;
figure;
d5=X_est(5,:);
plot(xvalue,d5);
hold on,
plot(wr);
legend('estimated value','actual value');
What is size(d5)?
If you are going to plot an x vs y, then the two must be of corresponding sizes, yes. You can either pick to plot the number of elements of the longer that matches the shorter or you can augment the shorter to the size of the longer with NaN which will be silently ignored by plot and friends. But, they must be commensurate in size
plot(wr) by itself will plot the elements of the array/vector wr against their ordinal number so doesn't matter how many elements there are in it...since you just use 1:N for a chosen N for the other plots, they could also just use the one-argument form and wouldn't have to worry about the lengths, specifically.
All depends upon what the data really represent and what you're trying to show which you don't supply sufficient context to be able to tell...

Community Treasure Hunt

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

Start Hunting!