开发者

Logical error in MATLAB

开发者 https://www.devze.com 2023-01-16 10:57 出处:网络
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
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

The output is

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

What is the logic behind the manner in which diag4 and diag5 have been gener开发者_运维知识库ated?


I'm not totally clear about your goal, still here's one way to extract the diagonals of an RGB image (diagonal of 2D matrices for each color channel):

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 will have three rows, each contain the (linear) indices of the diagonal elements (one for each slice). From there you can adapt it to your code...


The idea behind the above code is simple: take a 2D matrix, the diagonal elements can be accessed using:

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

then in the 3D case, I add an additional offset to reach the other slices in the same manner.


One way to access the diagonal elements of a matrix (get or assign) is to use sub2ind to find the entries:

>> 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

Second example:

% 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
0

精彩评论

暂无评论...
验证码 换一张
取 消