Search code examples
matlabmatrixdimensionsmismatch

MATLAB: Subscripted assignment dimension mismatch: y(:,:,j,i) = x;


I am trying to remove blank (=0) cols and rows from 2D images in 3D stack of images and then generate a new 3D stack:

for i=1:numVols;

     for j=1:numFrames; % Crop black boundaries
        tempvol = VolStack(:,:,j,i);
        tempvol(:,all(tempvol==0,1))=[];
        tempvol(all(tempvol==0,2),:)=[];
                VolStackTemp(:,:,j,i) = tempvol;
     end

end

The strange thing is that it works sometimes but most of the time I get an error due to the line:

VolStackTemp(:,:,j,i) = tempvol;

Subscripted assignment dimension mismatch

Any ideas why?


Solution

  • With the additional content from your comment, I would solve it this way:

    %get all cols which are zero in all slices
    h=all(all(VolStack==0,1),2)
    cidx=all(h,3)
    %same for rows
    ridx=all(h,4)
    %delete zero only rows and cols:
    VolStack=VolStack(:,:,~ridx,~cidx)
    

    This way your code will run faster and no nonzero data is deleted.