MATLAB plotting problems...
이전 댓글 표시
I have been trying to plot this graph on matlab or figure out how to go about doing it but everything I seem to do so far does not work. I was hoping I could get some help.
%%Define Variables
g = 9.8;
c = 14;
v=35;
%%Calculations
figure; hold on
for m = 60:70
y(m) = (14*35)/(m*9.8);
end
figure(1); plot(m,y(m));
xlim([60 70]);
댓글 수: 1
Stephen23
2017년 11월 3일
See Jan Simon's answer for the simplest solution.
채택된 답변
추가 답변 (2개)
Walter Roberson
2017년 10월 5일
3 개 추천
After the for loop m will be the scalar 70, not the range.
댓글 수: 6
David Oshidero
2017년 10월 5일
Walter Roberson
2017년 10월 5일
The following general pattern is useful:
%%Define Variables
g = 9.8;
c = 14;
v=35;
%%Calculations
figure; hold on
m_vals = 60:70;
num_m = length(m_vals);
y = zeros(1, num_m);
for m_idx = 1 : num_m
m = m_vals(m_idx);
y(m_idx) = (14*35)/(m*9.8);
end
plot(m_vals, y)
Walter Roberson
2017년 10월 5일
In the specialized case, the above can be abbreviated as
%%Define Variables
g = 9.8;
c = 14;
v=35;
%%Calculations
figure; hold on
y = zeros(1, 11);
for m = 60:70
y(m-60+1) = (14*35)/(m*9.8);
end
plot(60:70, y)
David Oshidero
2017년 10월 6일
David Oshidero
2017년 10월 6일
@David: It is a pre-allocation. The output array is created at once, because this is much cheaper than letting the array grow iteratively. Example:
x = [];
for k = 1:1e7
x(k) = k + rand;
end
Now in each iteration Matlab has to create a new array in the memory, which is 1 element larger than the old one, copy the former contents and insert the new value. Finally Matlab did not reserve memory for 1e6 elements, but for sum(1:1e7). For a double this needs 8 byte per element, such that 400 TB must be allocated and copied. This wastes a lot of time. To avoid this, the array is allocated before the loop:
x = zeros(1, 1e7);
for k = 1:1e7
x(k) = k + rand;
end
While the first version takes 1.75 sec, the second needs 0.45 sec only.
Well, this is the theory. Fortunately Matlab tries to reduce the drawbacks as good as possible. Even a fast processor could allocate and copy 400 TB in 1.75 seconds.
In your case the runtime does not matter. But the strategy in the forum is to teach good programming styles in general.
A simplified version of your code:
g = 9.8;
c = 14;
v = 35;
t = 60:70;
y = (14*35) ./ (m * 9.8); % [EDITED, fixed typo, thanks Walter!]
figure;
plot(m, y);
xlim([60 70]);
This is called "vectorizing": Matlab can perform the calculations with the vector m directly. This can be faster and nicer than the loop version, and it is less prone to bugs of indexing.
댓글 수: 2
Walter Roberson
2017년 10월 7일
The lines
t = 60:70;
y = (14*35) / (m * 9.8);
should be
m = 60:70;
y = (14*35) ./ (m * 9.8);
Jan
2017년 10월 9일
Thank you, Walter.
카테고리
도움말 센터 및 File Exchange에서 Graphics Performance에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
