Attempting to plot a function with a for loop, but nothing is working.
2 次查看(过去 30 天)
显示 更早的评论
This is my first time posting a question...I'm getting stuck on this portion of my code.
1: I can't seem to figure out why my function won't plot at all.
2: I can't figure out how to plot multiple lines on one plot.
figure(1);
for i = 1:2:50 %for loop to run for 2miles of radius, or 1 hr of time
con = (kilotons * (1.2*10^8))/(pi*i^2); %Formula for calculating the concentration at each interval
plot(i,con) %plots hours/radius against concentration
ylabel('Concentration'), xlabel('Time (hr)') %Labels plot
title('Decreasing Concentration By Hour')
grid on
hold on %Supposed to hold each plot as the for loop moves through its sequence
end
hold off
2 个评论
Michael Van de Graaff
2021-12-10
Presumably you meant
ydata= (ii*1.2*10^8)./(pi*xdata);
since kk hasn't been defined?
but yeah, that plots pretty lines. you can modify as follows:
figure(1);
for ii = 1:10
xdata = 1:2:50;
ydata= (ii*1.2*10^8)./(pi*xdata);
plot(xdata,ydata,'displayname',['ii = ',num2str(ii)]) % this will tell a legend object what to label, handy
ylabel('Concentration'), xlabel('Time (hr)')
title('Decreasing Concentration By Hour')
grid on
hold on
end
legend % without calling legend it won't show up.
Do keep in mind that legend is much slower than everything else in matlab.
采纳的回答
Michael Van de Graaff
2021-12-9
编辑:Michael Van de Graaff
2021-12-9
figure(1);
kilotons = 2; %i needed to add this
% i always use double indices ii,jj,kk, helps avoid confusing and also is
% i=sqrt(-1)?
for ii = 1:2:50 %for loop to run for 2miles of radius, or 1 hr of time
con(ii) = (kilotons * (1.2*10^8))/(pi*ii^2); %Formula for calculating the concentration at each interval
plot(ii,con(ii),'o') % the plotmarker 'o' is key if you INSIST on doing it this way %plots hours/radius against concentration
ylabel('Concentration'), xlabel('Time (hr)') %Labels plot
title('Decreasing Concentration By Hour')
grid on
hold on %Supposed to hold each plot as the for loop moves through its sequence
end
hold off
The important part is using plot works best with vectors, and it defaults to line plots, so your data ARE there, but the plot markers aren't visible.
I would do it this way:
figure(1);
kilotons = 2;
xdata = 1:2:50;
ydata= (kilotons*1.2*10^8)./(pi*xdata)
plot(xdata,ydata)
ylabel('Concentration'), xlabel('Time (hr)') %Labels plot
title('Decreasing Concentration By Hour')
grid on
更多回答(1 个)
David Hill
2021-12-9
kilotons=input('kilotons of blast');
i=1:2:50;
con = (kilotons * (1.2*10^8))./(pi*i.^2);
plot(i,con);
ylabel('Concentration'), xlabel('Time (hr)');
title('Decreasing Concentration By Hour');
grid on;
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!