% Define the matrix
M = cat(3, [4, 3; 6, 2], [7, 1; 5, 8]);

% Initialize figure
figure;

% Define the axes
ax = axes('XLim', [0 3], 'YLim', [0 3], 'ZLim', [0 3]);
view(3);
axis equal;
grid on;
hold on;

% Define colors
colors = lines(8);  % Just as an example, use 8 distinct colors

% Function to draw a single cube at position (x, y, z)
% with size s (scaled for visibility) and color c
function drawSingleCube(ax, x, y, z, s, c)
    % Define the vertices of a unit cube
    [X, Y, Z] = meshgrid([0 1]);
    % Make the cube vertices
    vertices = [X(:), Y(:), Z(:)];
    vertices = bsxfun(@plus, vertices, [x y z]);  % Shift the cube to the desired position
    vertices = bsxfun(@times, vertices, s);  % Scale the cube to the desired size
    
    % Define the faces of the cube
    faces = ...
    [1 2 4 3; ... % Front face
     2 6 8 4; ... % Right face
     6 5 7 8; ... % Back face
     5 1 3 7; ... % Left face
     3 4 8 7; ... % Top face
     5 6 2 1];    % Bottom face
    
    % Draw the cube
    patch('Vertices', vertices, 'Faces', faces, ...
          'FaceColor', c, 'Parent', ax, 'EdgeColor', 'none', 'FaceAlpha', 0.5);
end

% Iterate through each element of the matrix to draw the cubes
for z = 1:size(M,3)
    for y = 1:size(M,2)
        for x = 1:size(M,1)
            drawSingleCube(ax, x-1, y-1, z-1, M(x,y,z)/10, colors(mod(M(x,y,z)-1, size(colors, 1))+1, :));
        end
    end
end

% Adjust the view
view(3);
axis vis3d;
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
