# Matlab – 3D bars arrays without empty elements

Matlab Dec 13, 2012

bar3 is an useful command to illustrate multi-dimensional distributions.  If the colors of the beams represent its value, the diagram gives a  good overview. But the code examples given in the Matlab help work just  fine for matrices without “0” elements. The following figure shows a  bar3 diagram that includes values from 0 to 7. The colors of the “0”  elements are completely wrong.

Y=[0 0 0 3 5
0 2 5 7 0 ];
h=bar3(Y);
colorbar

Hence, a quite more representative way is to eliminate the zeros by  manipulating the zdata entries of the figure. Just by setting each zero  value on NaN it is invisible! Especially for larger diagrams the effect  looks nice.

Y=[0 0 0 3 5
0 2 5 7 0 ];

h=bar3(Y);
for i = 1:size(Y,2)
zdata = get(h(i),'zdata');
k = 1;
for j = 0:6:(6*size(Y,1)-6)
if Y(k,i)==0
zdata(j+1:j+6,:)= NaN;
end
k = k+1;
end
set(h(i),'zdata',zdata);
end

colorbar

Filtered bar3 diagram

The code was tested with Matlab 2008b