簡體   English   中英

如何在MATLAB中繪制矩陣列的直方圖?

[英]How to plot histogram of columns of a matrix in MATLAB?

我必須繪制MatrixE1每一列的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); 

您可以像這樣訪問 matrixE1 中的每個列:

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

...然后你可以簡單地使用命令 hist() 來繪制直方圖。 您可以將 matrixE1 中第一列的直方圖繪制為:

hist(firstCol);

如果我理解你的第二個問題: “我會怎么做? 歷史(??)。 如何獲得 matrixE1 的所有列的一個直方圖? 我應該做 hist(matrixE1) 嗎?''您可以在繪制一個柱狀圖的直方圖后簡單地使用命令保持。 然后在同一圖上繪制另一個直方圖。 例如,如果要將矩陣 E1 的第一列和第二列的直方圖繪制到同一個圖,您可以輸入:

hist(firstCol);
hold on;
hist(secondCol);
>> 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');

在此處輸入圖片說明

還有另一種更簡單但計算成本更高的方法:

plotmatrix(A)

對於任何矩陣 A,這將生成輸入矩陣的所有成對組合的 m×n 散點圖(不要對大矩陣執行此操作,大於屏幕上的大小)。


您在頂部獲得的是沿情節矩陣主對角線的直方圖。


由於使用過時函數hist其他答案 ( 1 , 2 ) 添加此答案。

MATLAB 建議避免使用hist ,現在支持histogram ( source )。 轉換很簡單。

直方圖顯示矩陣 A 的 3 個不同列的頻率。

% 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屬性從頻率(計數)調整到概率或概率密度函數(請參閱此處的文檔)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM