Matlab:repmat代码解释

时间:2017-09-06 03:37:58

标签: matlab histogram

任何人都可以解释下面突出显示的使用repmat的两行代码吗?这可以直接从MathWorks documentation for learning data analysis

获取
bin_counts = hist(c3);  % Histogram bin counts
N = max(bin_counts);    % Maximum bin count
mu3 = mean(c3);         % Data mean
sigma3 = std(c3);       % Data standard deviation

hist(c3) % Plot histogram
hold on
plot([mu3 mu3],[0 N],'r','LineWidth',2) % Mean
% --------------------------------------------------------------
X = repmat(mu3+(1:2)*sigma3,2,1);       % WHAT IS THIS?
Y = repmat([0;N],1,2);                  % WHY IS THIS NECESSARY?
% --------------------------------------------------------------
plot(X,Y,'g','LineWidth',2) % Standard deviations
legend('Data','Mean','Stds')
hold off

有人可以向我解释X = repmat(...)行吗?我知道它将被绘制为1和2标准差线。

另外,我尝试评论Y = ...行,情节看起来完全相同,那么这条线的目的是什么?

由于

1 个答案:

答案 0 :(得分:2)

让我们将表达式分解为多个语句

X = repmat(mu3+(1:2)*sigma3,2,1);

相当于

% First create a row vector containing one and two standard deviations from the mean.
% This is equivalent to xvals = [mu3+1*sigma3, mu3+2*sigma3];
xval = mu3 + (1:2)*sigma3;

% Repeat the matrix twice in the vertical dimension. We want to plot two vertical
% lines so the first and second point should be equal so we just use repmat to repeat them.
% This is equivalent to
% X = [xvals;
%      xvals];
X = repmat(xval,2,1);

% To help understand how repmat works, if we had X = repmat(xval,3,2) we would get
% X = [xval, xval;
%      xval, xval;
%      xval, xval];

Y矩阵的逻辑类似,只是它在列方向上重复。你最终会和

结合在一起
X = [mu3+1*sigma3, mu3+2*sigma3;
     mu3+1*sigma3, mu3+2*sigma3];
Y = [0, 0;
     N, N];

调用绘图时,它会在XY矩阵的每列中绘制一行。

plot(X,Y,'g','LineWidth',2);

相当于

plot([mu3+1*sigma3; mu3+1*sigma3], [0, N], 'g','LineWidth',2);
hold on;
plot([mu3+2*sigma3; mu3+2*sigma3], [0, N], 'g','LineWidth',2);

绘制两条垂直线,与平均值相差一,两个标准差。

如果您注释掉Y,则Y未定义。代码仍然有效的原因可能是Y的先前值仍存储在工作空间中。如果在再次运行脚本之前运行命令clear,您会发现plot命令将失败。