Why is my plot plotting blank?

조회 수: 197 (최근 30일)
Xingkai Yang
Xingkai Yang 2015년 11월 2일
댓글: John 2015년 11월 4일
>> t = 0:20;
>> Vx = 1000;
>> for ii = 1:2:length(t)
Vx = Vx - (0.0004*Vx^2)*t(ii)
end
Vx =
1000
Vx =
200
Vx =
136
Vx =
91.6096
Vx =
64.7542
Vx =
47.9818
Vx =
36.9310
Vx =
29.2931
Vx =
23.8014
Vx =
19.7225
Vx =
16.6107
>> plot (t,Vx)
  댓글 수: 1
John
John 2015년 11월 4일
You are plotting a single point. You are overwriting Vx every loop iteration. You need to index Vx. Try this:
t = 0:20;
Vx = zeros(size(t));
Vx(1) = 1000;
for ii = 2:length(t)
Vx(ii) = Vx(ii - 1) - (0.0004*Vx(ii - 1)^2)*t(ii);
end
figure, plot(t, Vx)

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

답변 (2개)

Walter Roberson
Walter Roberson 2015년 11월 2일
Your plot is not empty. You can see that with a minor change:
plot (t,Vx, '*')
You should ask yourself how many items are in t and how many items are in Vx
  댓글 수: 1
Xingkai Yang
Xingkai Yang 2015년 11월 2일
Thank you very much. I see I have t 0 to 20 and only have one value in Vx. I wanted to plot all the values of Vx during for loop, so what should do for this?

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


Nitin Khola
Nitin Khola 2015년 11월 4일
편집: Nitin Khola 2015년 11월 4일
As Walter has mentioned, Vx in this case is a scalar. Refer to the last bullet in the description for plot(X,Y) by following the link below: http://www.mathworks.com/help/matlab/ref/plot.html#description
Your code indicates that you have a variable "Vx" that is dependent on the variable "t". Also, most for loops can be avoided as discussed in following documentation. http://www.mathworks.com/help/matlab/matlab_prog/vectorization.html
If there is no possibility for eliminating the "for" loop, you can do data linking so that the plot updates its data. Refer to the following documentation for details on data linking: http://www.mathworks.com/help/matlab/data_analysis/making-graphs-responsive-with-data-linking.html
I do not recommend it as it will seriously affect the performance of the code, however, just for illustration purposes, you can modify your existing code to include a "hold on" and a "scatter" in the loop. Note, that I do not recommend it. It will just help you see how these commands work.
for ii = 1:2:length(t)
Vx = Vx - (0.0004*Vx^2)*t(ii)
scatter(t(ii),Vx);
hold on
end
I would suggest reading in detail about vectorization and data linking is the best approach.

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by