Remove the air bubbles
Given a matrix a, return a matrix b in which all the zeros have "bubbled" to the top. That is, any zeros in a given column should be moved to the top. The order of the remaining nonzero numbers in the column should be preserved.
Input a = [ 1 2 3
0 4 5
6 0 0 ]
Output b is [ 0 0 0
1 2 3
6 4 5 ]
Function:
function zo = bubbles(x)
[r c]=size(x);
zo=[];
for j=1:c
Y=[];
for i=1:r
Y=[Y x(i,j)];
end
d=0;
for u=1:r
if(Y(u)==0)
d=d+1;
end
end
t=[];
for rp=1:d
t=[t 0];
end
for h=1:r
if(Y(h)~=0)
t=[t Y(h)];
end
end
zo=[zo t'];
end
end
Input a = [ 1 2 3
0 4 5
6 0 0 ]
Output b is [ 0 0 0
1 2 3
6 4 5 ]
MATLAB CODE:
clc
x=input('Enter the matrix:');
[r c]=size(x);
zo=[];
for j=1:c
Y=[];
for i=1:r
Y=[Y x(i,j)];
end
d=0;
for u=1:r
if(Y(u)==0)
d=d+1;
end
end
t=[];
for rp=1:d
t=[t 0];
end
for h=1:r
if(Y(h)~=0)
t=[t Y(h)];
end
end
zo=[zo t'];
end
disp(zo);
Explanation:
Sample Output:
[r c]=size(x);
zo=[];
for j=1:c
Y=[];
for i=1:r
Y=[Y x(i,j)];
end
d=0;
for u=1:r
if(Y(u)==0)
d=d+1;
end
end
t=[];
for rp=1:d
t=[t 0];
end
for h=1:r
if(Y(h)~=0)
t=[t Y(h)];
end
end
zo=[zo t'];
end
end
No comments