在Matlab中没有循环地对数组中的每个元素进行Bitshift

时间:2016-12-01 14:41:57

标签: matlab bit-shift

我有一个16位/像素的图像文件。使用Matlab,我想生成另一个数组,其中每个元素只包含2-10位。我可以在for循环中完成它,但它太慢了:

if mod(j,2) ~= 0       
   image1(i,j) = bitshift(image(i,j),-2);    % shift the LL bits to the left
else            
   tmp = bitand(image(i,j),3);          % save off the lower 2 bits 00000011
   adder = bitshift(tmp,6);             % shift to new positions in LL
   image1(i,j) = bitshift(image(i,j),-2);  % shift the UL bits to the right
   image1(i,j-1) = bitor(image1(i,j-1),adder);  add in the bits from the UL
end

有没有办法做类似以下的事情?

 image1(:,1:2:end) = bitshift(image(:,1:2:end),-2); 
 etc

1 个答案:

答案 0 :(得分:0)

bitshiftbitandbitor调用全部作为第一个输入在多维数组上运行。您之前看到的问题很可能是因为您已将image1初始化为与image不同的尺寸,因此您使用以下命令获得尺寸不匹配错误

 image1(:,1:2:end) = bitshift(image(:,1:2:end),-2); 

要解决此问题,请在调用上述命令之前将image1初始化为image或大小为image的零数组

image1 = zeros(size(image));
image1(:,1:2:end) = bitshift(image(:,1:2:end),-2);