简体   繁体   中英

How to pad zeros in matrix in matlab

I have two matrices: finalEnergy{1,j}(i) and finalZC{1,j}(i) . The finalEnergy{1,1}(i) has 1 x 611 elements and finalZC{1,1}(i) has 595 elements. I have to pad finalZC{1,1}(i) to have 611 elements. how to pad the size of each cell of finalZC{i,j} to the size of cells in finalEnergy{i,j} . My code is below

for j=1:length(finalEnergy)
  for i=1:length(finalEnergy{1,j})
    if(length(finalEnergy{1,j})<length(finalZC{1,j}))

      lenFE=length(finalZC{1,j})-length(finalEnergy{1,j});

      finalEnergy{1,j})(i)=padarray(finalEnergy,lenFE,padding);
    end 
  end
end   

You have a few bugs and implementation errors in your loop, but the idea is right. You do not need to loop over i here, if I understand you correctly.

for j=1:size(finalEnergy, 2)
    if(numel(finalEnergy{1, j})>numel(finalZC{1, j})) 
        lenFE=length(finalEnergy{1, j})-length(finalZC{1, j});  
        finalZC{1, j}=padarray(finalZC{1, j},[0 lenFE/2], 0);
    end
end

There must be a more efficient way to do this. This also assumes that lenFE is always an even number, which is correct in your case. I might edit this answer later to put in a more general solution..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM