1

I have a 256x256 matrix from that I want to create block of 8x8 matrices. I have a below code which shows just one block i want all the blocks then subtract a number from each element of the matrix. When i do the subtract 128 from each element it doesn't show negative values rather showing only 0.

[x,y] = size(M);

for i=1:8
   for j=1:8
      k(i,j) = M(i,j);
   end
end

disp(k);

for a=1:size(k)
   for b=1:size(k)
     A(a,b) = k(a,b) - 128;
   end
end

disp(A);
4

2 回答 2

1

好吧,如果你必须减去一个固定值,最好这样做

M = M - 128;

它更快。

你说你得到0的是价值而不是消极的;这可能是由于矩阵的类型unsigned(即这些人只是积极的)。转换为一般整数是必要的。尝试:

M = int16(M) - 128;

为了获得我提出的分区,可以有更有效的方法,顺便说一句:

r = rand(256,256);            %// test case, substitute with your matrix M
[i j] = meshgrid(1:8:256);    %// lattice of indices      
idx = num2cell([ i(:) , j(:) ],2); %// cell version 

matr = cellfun( @(i) r(i(1):i(1)+7,i(2):i(2)+7), idx, 'UniformOutput',false); %// blocks

matr 将按字典顺序包含所有子矩阵。例如

matr{2}

ans =

0.4026    0.3141    0.4164    0.5005    0.6952    0.1955    0.9803    0.5097
0.8186    0.9280    0.1737    0.6133    0.8562    0.7405    0.8766    0.0975
0.2704    0.8333    0.1892    0.7661    0.5168    0.3856    0.1432    0.9958
0.9973    0.8488    0.6937    0.2630    0.1004    0.5842    0.1844    0.5206
0.4052    0.0629    0.6982    0.1530    0.9234    0.1271    0.7317    0.3541
0.2984    0.3633    0.1510    0.0297    0.0225    0.7945    0.2925    0.0396
0.5097    0.0802    0.8744    0.1032    0.8523    0.6150    0.4845    0.5703
0.8635    0.0194    0.1879    0.5017    0.5297    0.6319    0.2406    0.5125

说明:在 matlab 中,您可以有效地对矩阵和它们的切片进行操作。例如,您可以轻松复制子矩阵,例如第一个 8x8 矩阵是

  sub = M(1:8,1:8);

你想要所有的子矩阵,因此你需要一种索引格来获得

  sub_ij = M(1+8*(i-1) : 7 * 8*(i-1) , 1+8*(j-1) : 7 * 8*(j-1))

即你需要格子

  (1+8*(i-1) : 7 * 8*(i-1) , 1+8*(j-1) : 7 * 8*(j-1))   % // for all i,j

你可以使用meshgrid它。

最后你必须切断碎片,这就是最后两条指令所做的。特别是第一个生成索引(try idx{1},...),第二个生成子矩阵(try matr{1},...)。

于 2012-11-27T21:03:22.743 回答
0

希望这段代码对您有所帮助。它具有 16x16 的图像,可分为 4x4 块。您可以根据需要更改值并获得所需的输出。

于 2012-11-28T03:50:34.153 回答