Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

image processing - Logical error in MATLAB

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...