Transform 3D binary matrix into 2D

1 view (last 30 days)
Jan Kubicek
Jan Kubicek on 13 Apr 2021
Answered: Jan on 13 Apr 2021
Dear colleagues,
I would like to kindly ask you for the help with the transformation from 3D into 2D matrix. Supposing that I have stored the binary image in the variable seg1, containing 45 layers (seg1(:,:,45)). I need to make the 2D matrix with the same dimension(rows and columns) as seg1 with keeping the same pixel values: original=1, result=1 and original=0, result=0. Here is my code, but it does not work well. Thank you very much for your help.
[row col lev]=size(seg1);
seg2=zeros(row,col);
for i=1:lev
for j=1:row
for k=1:col
if seg1(j,k,i)=1
seg2(j,k)=1;
else
seg2(j,k)=0;
end
end
end
end

Answers (1)

Jan
Jan on 13 Apr 2021
Your code overwrites the output for each loop over i=1:lev. An equivalent code without a loop:
%seg2 = seg1(:, :, end);
What should happen with the 45 bits of the input? Do you want to store them as bits of integer values?
seg1 = randi([0,1], 3,4,5);
[row, col, lev] = size(seg1);
tmp = reshape(seg1, row*col, lev) * pow2(lev-1:-1:0).';
seg2 = reshape(tmp, row, col);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!