Search code examples
matlab3dmatlab-figureprobability

Plotting a 3d figure in Matlab given a table


The table I have is like this: An image of the table

X↓ Y-> Y = 0 Y = 1 Y = 2 Y = 3
X = 3 PXY = 4/54 PXY = 3/54 PXY = 2/54 PXY = 1/54
X = 5 PXY = 6/54 PXY = 5/54 PXY = 4/54 PXY = 3/54
X = 7 PXY = 8/54 PXY = 7/54 PXY = 6/54 PXY = 5/54

PXY is given by (x - y + 1)/54

How should I go about graphing this on MATLAB? I wish to draw a 3d histogram, something like this:

plot.

Most of my attempts have ended in errors usually because the X and Y vectors are not the same length.

If there's ways to do this Python as well, then please let me know, that works too.


Solution

  • In Matlab, you can use histogram2 specifying the edges of the bins in the x and y direction and the bin count.

    % Your data
    x = [3; 5; 7];
    y = [0, 1, 2, 3];
    p = (x - y + 1)/54;
    % since x is a column vector and y a row vector, as of Matlab R2016b this results in a length(x)*length(y) matrix, equivalent to:
    % p = zeros(length(x), length(y));
    % for ix = 1:length(x)
    %    for iy = 1:length(y)
    %        p(ix, iy) = (x(ix) - y(iy) + 1)/54;
    %    end
    % end
    
    % Plot the histogram
    histogram2('XBinEdges', [x; 9], ...
               'YBinEdges', [y, 4], ...
               'BinCounts', p);
    xlabel('X')
    ylabel('Y')
    zlabel('P_{xy}')
    

    Since you need 3 bins for x (4 bins for y), you need to provide 4 edges (5 edges for y), hence the additional points in the histogram2 call.

    EDIT: on second thought, you probably want the bins centered on the x and y points that you provide, so perhaps you might want to use xEdges = [x - 1; x(end) + 1] and yEdges = [y - 0.5, y(end) + 0.5] as bin edges instead.