Main Content

实时编辑器介绍

以下示例是对实时编辑器的介绍。在实时编辑器中,可以创建随代码一起显示代码输出的实时脚本。添加格式化文本、方程、图像和超链接用于增强您的记叙脚本,以及将实时脚本作为交互式文档与其他人共享。

在实时编辑器中创建实时脚本。要创建实时脚本,请在主页选项卡上,点击新建实时脚本

添加人口统计数据

将实时脚本划分为多个节。每一节均可以包含文本、代码和输出。MATLAB® 代码显示为灰色背景,输出显示为白色背景。要创建新的节,请转至实时编辑器选项卡,然后点击分节符按钮。

添加 1900 至 2000 年间美国的人口统计数据。

years = (1900:10:2000);                                  % Time interval
pop = [75.995 91.972 105.711 123.203 131.669 ...         % Population Data
   150.697 179.323 213.212 228.505 250.633 265.422]
pop = 1×11

   75.9950   91.9720  105.7110  123.2030  131.6690  150.6970  179.3230  213.2120  228.5050  250.6330  265.4220

以可视方式呈现一段时间内的人口变化

各节可独立运行。要运行某节中的代码,请转至实时编辑器选项卡,然后点击运行节按钮。您也可以点击在将鼠标移至节左侧时显示的蓝条。运行节时,输出和图窗会随生成这些内容的代码一起显示。

绘制不同年份的人口数据图。

plot(years,pop,'bo');                                    % Plot the population data
axis([1900 2020 0 400]);
title('Population of the U.S. 1900-2000');
ylabel('Millions');
xlabel('Year')
ylim([50 300])

Figure contains an axes object. The axes object with title Population of the U.S. 1900-2000, xlabel Year, ylabel Millions contains a line object which displays its values using only markers.

是否可以预测 2010 年的美国人口?

拟合数据

将支持信息添加到文本中,包括方程、图像和超链接。

下面我们尝试使用多项式拟合数据。我们将使用 MATLAB polyfit 函数获取系数。

拟合方程为:

y=ax+blineary=ax2+bx+cquadraticy=ax3+bx2+cx+d.cubic

x = (years-1900)/50;
coef1 = polyfit(x,pop,1) 
coef1 = 1×2

   98.9924   66.1296

coef2 = polyfit(x,pop,2)
coef2 = 1×3

   15.1014   68.7896   75.1904

coef3 = polyfit(x,pop,3)
coef3 = 1×4

  -17.1908   66.6739   29.4569   80.1414

绘制曲线图

创建具有任意数量的文本和代码行的节。

我们可以绘制用于拟合数据的线性、二次和立方曲线。我们使用 polyval 函数来计算在点 x 处的拟合多项式。

pred1 = polyval(coef1,x);
pred2 = polyval(coef2,x);
pred3 = polyval(coef3,x);
[pred1; pred2; pred3]
ans = 3×11

   66.1296   85.9281  105.7266  125.5250  145.3235  165.1220  184.9205  204.7190  224.5174  244.3159  264.1144
   75.1904   89.5524  105.1225  121.9007  139.8870  159.0814  179.4840  201.0946  223.9134  247.9403  273.1753
   80.1414   88.5622  101.4918  118.1050  137.5766  159.0814  181.7944  204.8904  227.5441  248.9305  268.2243

下面我们绘制每个多项式的预测值。

hold on
plot(years,pred1)
plot(years,pred2)
plot(years,pred3)
ylim([50 300])
legend({'Data' 'Linear' 'Quadratic' 'Cubic'},'Location', 'NorthWest')
hold off

Figure contains an axes object. The axes object with title Population of the U.S. 1900-2000, xlabel Year, ylabel Millions contains 4 objects of type line. One or more of the lines displays its values using only markers These objects represent Data, Linear, Quadratic, Cubic.

预测人口

您可以将您的实时脚本与其他 MATLAB 用户共享,这样他们可以重现您的结果。您也可以将结果发布为 PDF、Microsoft® Word 或 HTML 文档。在实时脚本中添加控件,可以向用户展示重要参数会对分析产生怎样的影响。要添加控件,请转至实时编辑器选项卡,点击控件按钮,然后从可用选项中进行选择。

我们现在可以使用三个方程计算预测的给定年份的人口。

year = 2018;
xyear = (year-1900)/50;
pred1 = polyval(coef1,xyear);
pred2 = polyval(coef2,xyear);
pred3 = polyval(coef3,xyear);
[pred1 pred2 pred3]
ans = 1×3

  299.7517  321.6427  295.0462

以 2010 年为例,线性拟合和三次拟合的预测值相似,约为 2.84 亿人口,而二次拟合的预测值更高,约为 3 亿人口。

相关主题