MATLAB中的逻辑错误

时间:2010-09-13 14:44:15

标签: matlab image-processing

a4 = 10*magic(4);
a5 = magic(5);
a4
a5

diag4 = sub2ind([4,4], 1:3,1:3);
diag5 = sub2ind([5,5], 1:3,1:3);
a5(diag5) = a4(diag4)    #Display changed contents
diag4   %#  Display diagonal of magic4
diag5  %# Display diagonal of magic5

a4(diag4)=a5(diag5) %# Recovering the original

输出

a4 =                     %# Display of original a4 magic square

   160    20    30   130
    50   110   100    80
    90    70    60   120
    40   140   150    10

a5 =               %#Display of original magic square
    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

diag4 =
     1     6    11

diag5 =
     1     7    13

a5 =
   160    24     1     8    15
    23   110     7    14    16
     4     6    60    20    22
    10    12    19    21     3
    11    18    25     2     9

a4 =
   160    20    30   130
    50   110   100    80
    90    70    60   120
    40   140   150    10

生成diag4和diag5的方式背后的逻辑是什么?

2 个答案:

答案 0 :(得分:1)

我不完全清楚你的目标,仍然是提取RGB图像对角线的一种方法(每个颜色通道的2D矩阵的对角线):

A = rand(32,32,3);   %# it can be any 3D matrix (and not necessarily square)
[r c d] = size(A);
diagIDX = bsxfun(@plus, 1:r+1:r*c, (0:d-1)'.*r*c);
A( diagIDX(:) )

diagIDX将有三行,每行包含对角元素的(线性)索引(每个切片一个)。从那里你可以根据你的代码进行调整......


上述代码背后的想法很简单:采用2D矩阵,可以使用以下方法访问对角元素:

A = rand(5,4);
[r c] = size(A);
A( 1:r+1:r*c )

然后在3D情况下,我添加了一个额外的偏移量,以相同的方式到达其他切片。

答案 1 :(得分:0)

访问矩阵的对角元素(获取或分配)的一种方法是使用sub2ind来查找条目:

>> a = magic(4);
>> ind = sub2ind([4,4], 1:3,1:3);
>> a(ind) = rand(1,3)

a =

    0.6551    2.0000    3.0000   13.0000
    5.0000    0.1626   10.0000    8.0000
    9.0000    7.0000    0.1190   12.0000
    4.0000   14.0000   15.0000    1.0000

第二个例子:

% Replace the first 3 items in the diagonal of a5 by 
% the first 3 items in the diagonal of a4.
>> a4 = 10*magic(4);
>> a5 = magic(5);
>> diag4 = sub2ind([4,4], 1:3,1:3);
>> diag5 = sub2ind([5,5], 1:3,1:3);
>> a5(diag5) = a4(diag4)

a5 =

   160    24     1     8    15
    23   110     7    14    16
     4     6    60    20    22
    10    12    19    21     3
    11    18    25     2     9