【问题标题】:How to plot histogram of columns of a matrix in MATLAB?如何在MATLAB中绘制矩阵列的直方图?
【发布时间】:2016-10-14 03:33:04
【问题描述】:

我必须绘制MatrixE1 的每一列的直方图。我该怎么做呢?这是我到目前为止所写的。

% Create a random 5 x 3 matrix filled with random values between 0 and 10
a0 = 0;
b0 = 10;
r = a0 + (b0-a0).*rand(1,1);
matrixA = [randi([0 10]) randi([0 10]) randi([0 10]); randi([0 10]) randi([0 10]) randi([0 10]); randi([0 10]) randi([0 10]) randi([0 10]); randi([0 10])      randi([0 10]) randi([0 10]); randi([0 10]) randi([0 10]) randi([0 10])]
% Create identity matrix 3 x 3 
matrixB = eye(3,3) 

% Create new submatrix of A with the last 3 rows
matrixC =  matrixA(end-2 : end, :) 

%  Pair wise multiplication of C and B
matrixD = times(matrixC, matrixB)  

%  Concatenate Matrix A and D
matrixE1 = [matrixA ; matrixD]

% Plot histogram of columns. 
matrixColumn1 = matrixE1(1 : end , end-2: end-2);  
matrixFColumn2 = matrixE1(1 : end, end -1 : end-1);
matrixFColumn3 = matrixE1(1 : end, end : end); 

【问题讨论】:

  • 你试过hist()吗?
  • 我该怎么办?历史(??)。如何获得 matrixE1 的所有列的一个直方图?我应该做 hist(matrixE1) 吗?

标签: matlab matrix plot histogram


【解决方案1】:

您可以像这样访问 matrixE1 中的每个列:

firstCol = matrixE1(:,1);
secondCol = matrixE1(:,2);
thirdCol = matrixE1(:,3);

...然后您可以简单地使用命令 hist() 来绘制直方图。您可以将 matrixE1 中第一列的直方图绘制为:

hist(firstCol);

如果我理解您的第二个问题: ''我该怎么办?历史(??)。如何获得 matrixE1 的所有列的一个直方图?我应该做 hist(matrixE1) 吗?'' 在绘制一列的直方图后,您可以简单地使用命令 hold on。然后在同一图上绘制另一个直方图。例如,如果您想将 matrixE1 中第一列和第二列的直方图绘制到同一个图上,您可以输入:

hist(firstCol);
hold on;
hist(secondCol);

【讨论】:

【解决方案2】:
>> v1=randn(1000,1); % zero mean, unity stdev
>> v2=randn(1000,1)+1; % mean at one, unity stdev
>> V=[v1 v2]; % 1000 x 2 matrix
>> hist(V,100); % 100 bins
>> legend('v1', 'v2');

【讨论】:

【解决方案3】:

还有另一种更简单但计算成本更高的方法:

plotmatrix(A)

对于任何矩阵 A,这将生成输入矩阵的所有成对组合的 m×n 散点图(不要对大型矩阵执行此操作,大于您的屏幕可以容纳的大小)。


您在顶部获得的是沿绘图矩阵主对角线的直方图。


【讨论】:

  • 这是一个绝妙的技巧。一个注释....这如何解决OP's comment 希望所有列都在同一个直方图中可视化的问题?当我运行您的代码时,它会将它们放在沿主对角线的单独子图中。
  • 正确,我错过了他的那部分要求。在那种情况下,我会覆盖输出中的各个图。您的解决方案更完整,需要对数据有所了解才能正确扩展,是吗?
  • 鉴于 MATLAB 矩阵的性质,我不确定是否需要过多的理解。但无论情节如何,在一个可视化(或不同的域尺度)中塞入太多内容都会有实际限制,这对于任何方法都会发生。
【解决方案4】:

由于其他答案(12)使用过时的函数hist而添加此答案。

MATLAB 建议避免使用 hist,现在更倾向于使用 histogram (source)。转换很简单。

% MATLAB R2019a
% Sample Data
NumPoints = 2000;
a1 = 10*rand(NumPoints,1);
a2 = wblrnd(3,7,NumPoints,1);
a3 = 7 + 0.75*randn(NumPoints,1);
A = [a1 a2 a3];                      % Data Matrix

% Implement Sturges Rule for n<=500, Scott's Rule for n>500
nbinsh =@(n) ceil((1 + 3.3*log10(n))*(n<=500) + ((5/3)*(n^(1/3)))*(n>500));
NumBins = nbinsh(NumPoints);

numCols = size(A,2);

% Plot
figure, hold on
for k = 1:numCols
    histogram(A(:,k),'NumBins',NumBins,'DisplayName',['Col ' num2str(k)]);
end
legend('show')

您可以使用 Normalization 属性(参见 documentation here)根据应用程序需要从频率(计数)调整为概率或概率密度函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多