2-D cross-correlation - MATLAB xcorr2 (2024)

2-D cross-correlation

collapse all in page

Syntax

c = xcorr2(a,b)

c = xcorr2(a)

Description

example

c = xcorr2(a,b) returns the cross-correlation of matrices a and b with no scaling. xcorr2 is the two-dimensional version of xcorr.

c = xcorr2(a) is the autocorrelation matrix of input matrix a. This syntax is equivalent to xcorr2(a,a).

Examples

collapse all

Output Matrix Size and Element Computation

Open Live Script

Create two matrices, M1 and M2.

M1 = [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];M2 = [8 1 6; 3 5 7; 4 9 2];

M1 is 5-by-5 and M2 is 3-by-3, so their cross-correlation has size (5+3-1)-by-(5+3-1), or 7-by-7. In terms of lags, the resulting matrix is

C=(c-2,-2c-2,-1c-2,0c-2,1c-2,2c-2,3c-2,4c-1,-2c-1,-1c-1,0c-1,1c-1,2c-1,3c-1,4c0,-2c0,-1c0,0c0,1c0,2c0,3c0,4c1,-2c1,-1c1,0c1,1c1,2c1,3c1,4c2,-2c2,-1c2,0c2,1c2,2c2,3c2,4c3,-2c3,-1c3,0c3,1c3,2c3,3c3,4c4,-2c4,-1c4,0c4,1c4,2c4,3c4,4).

As an example, compute the element c0,2 (or C(3,5) in MATLAB®, since M2 is 3-by-3). Line up the two matrices so their (1,1) elements coincide. This placement corresponds to c0,0. To find c0,2, slide M2 two rows to the right.

2-D cross-correlation - MATLAB xcorr2 (1)

Now M2 is on top of the matrix M1(1:3,3:5). Compute the element-by-element products and sum them. The answer should be

1×8+7×3+13×4+8×1+14×5+20×9+15×6+16×7+22×2=585.

[r2,c2] = size(M2);CC = sum(sum(M1(0+(1:r2),2+(1:c2)).*M2))
CC = 585

Verify the result using xcorr2.

D = xcorr2(M1,M2);DD = D(0+r2,2+c2)
DD = 585

Two-Dimensional Cross-Correlation of Arbitrary Complex Matrices

Open Live Script

Given a matrix X of size M×N and a matrix H of size P×Q, their two-dimensional cross-correlation, C=XH, is a matrix of size (M+P-1)×(N+Q-1) with elements

C(k,l)=Tr{XHkl}1kM+P-1,1lN+Q-1.

Tr is the trace and the dagger denotes Hermitian conjugation. The matrices X and Hkl have size (M+2(P-1))×(N+2(Q-1)) and nonzero elements given by

X(m,n)=X(m-P+1,n-Q+1),PmM+P-1,QnN+Q-1

and

Hkl(p,q)=H(p-k+1,q-l+1),kpP+k-1,lqQ+l-1.

Calling xcorr2 is equivalent to this procedure for general complex matrices of arbitrary size.

Create two complex matrices, X of size 7×22 and H of size 6×17.

X = randn([7 22])+1j*randn([7 22]);H = randn([6 17])+1j*randn([6 17]);[M,N] = size(X);m = 1:M;n = 1:N;[P,Q] = size(H);p = 1:P;q = 1:Q;

Initialize X and C.

Xt = zeros([M+2*(P-1) N+2*(Q-1)]);Xt(m+P-1,n+Q-1) = X;C = zeros([M+P-1 N+Q-1]);

Compute the elements of C by looping over k and l. Reset Hkl to zero at each step. Save time and memory by summing element products instead of multiplying and taking the trace.

for k = 1:M+P-1 for l = 1:N+Q-1 Hkl = zeros([M+2*(P-1) N+2*(Q-1)]); Hkl(p+k-1,q+l-1) = H; C(k,l) = sum(sum(Xt.*conj(Hkl))); endendmax(max(abs(C-xcorr2(X,H))))
ans = 1.5139e-14

The answer coincides to machine precision with the output of xcorr2.

Align Two Images Using Cross-Correlation

Open Live Script

Use cross-correlation to find where a section of an image fits in the whole. Cross-correlation enables you to find the regions in which two signals most resemble each other. For two-dimensional signals, like images, use xcorr2.

Load a black-and-white test image into the workspace. Display it with imagesc.

load durerimg = X;White = max(max(img));imagesc(img)axis image offcolormap graytitle('Original')

2-D cross-correlation - MATLAB xcorr2 (2)

Select a rectangular section of the image. Display the larger image with the section missing.

x = 435;X = 535;szx = x:X;y = 62;Y = 182;szy = y:Y;Sect = img(szx,szy);kimg = img;kimg(szx,szy) = White;kumg = White*ones(size(img));kumg(szx,szy) = Sect;subplot(1,2,1)imagesc(kimg)axis image offcolormap graytitle('Image')subplot(1,2,2)imagesc(kumg)axis image offcolormap graytitle('Section')

2-D cross-correlation - MATLAB xcorr2 (3)

Use xcorr2 to find where the small image fits in the larger image. Subtract the mean value so that there are roughly equal numbers of negative and positive values.

nimg = img-mean(mean(img));nSec = nimg(szx,szy);crr = xcorr2(nimg,nSec);

The maximum of the cross-correlation corresponds to the estimated location of the lower-right corner of the section. Use ind2sub to convert the one-dimensional location of the maximum to two-dimensional coordinates.

[ssr,snd] = max(crr(:));[ij,ji] = ind2sub(size(crr),snd);figureplot(crr(:))title('Cross-Correlation')hold onplot(snd,ssr,'or')hold offtext(snd*1.05,ssr,'Maximum')

2-D cross-correlation - MATLAB xcorr2 (4)

Place the smaller image inside the larger image. Rotate the smaller image to comply with the convention that MATLAB® uses to display images. Draw a rectangle around it.

img(ij:-1:ij-size(Sect,1)+1,ji:-1:ji-size(Sect,2)+1) = rot90(Sect,2);imagesc(img)axis image offcolormap graytitle('Reconstructed')hold onplot([y y Y Y y],[x X X x x],'r')hold off

2-D cross-correlation - MATLAB xcorr2 (5)

Recovery of Template Shift with Cross-Correlation

Open Live Script

Shift a template by a known amount and recover the shift using cross-correlation.

Create a template in an 11-by-11 matrix. Create a 22-by-22 matrix and shift the original template by 8 along the row dimension and 6 along the column dimension.

template = 0.2*ones(11);template(6,3:9) = 0.6;template(3:9,6) = 0.6;offsetTemplate = 0.2*ones(22);offset = [8 6];offsetTemplate((1:size(template,1))+offset(1), ... (1:size(template,2))+offset(2)) = template;

Plot the original and shifted templates.

imagesc(offsetTemplate)colormap grayhold onimagesc(template)axis equal

2-D cross-correlation - MATLAB xcorr2 (6)

Cross-correlate the two matrices and find the maximum absolute value of the cross-correlation. Use the position of the maximum absolute value to determine the shift in the template. Check the result against the known shift.

cc = xcorr2(offsetTemplate,template);[max_cc, imax] = max(abs(cc(:)));[ypeak, xpeak] = ind2sub(size(cc),imax(1));corr_offset = [(ypeak-size(template,1)) (xpeak-size(template,2))];isequal(corr_offset,offset)
ans = logical 1

The shift obtained from the cross-correlation equals the known template shift in the row and column dimensions.

GPU Acceleration for Cross-Correlation Matrix Computation

This example uses:

  • Signal Processing ToolboxSignal Processing Toolbox
  • Parallel Computing ToolboxParallel Computing Toolbox

Open Live Script

This example requires Parallel Computing Toolbox™ software. Refer to GPU Computing Requirements (Parallel Computing Toolbox) to see what GPUs are supported.

Shift a template by a known amount and recover the shift using cross-correlation.

Create a template in an 11-by-11 matrix. Create a 22-by-22 matrix and shift the original template by 8 along the row dimension and 6 along the column dimension.

template = 0.2*ones(11); template(6,3:9) = 0.6; template(3:9,6) = 0.6;offsetTemplate = 0.2*ones(22); offset = [8 6];offsetTemplate((1:size(template,1))+offset(1), ... (1:size(template,2))+offset(2)) = template;

Put the original and shifted template matrices on your GPU using gpuArray objects.

template = gpuArray(template);offsetTemplate = gpuArray(offsetTemplate);

Compute the cross-correlation on the GPU.

cc = xcorr2(offsetTemplate,template);

Return the result to the MATLAB® workspace using gather. Use the maximum absolute value of the cross-correlation to determine the shift, and compare the result with the known shift.

cc = gather(cc);[max_cc,imax] = max(abs(cc(:)));[ypeak,xpeak] = ind2sub(size(cc),imax(1));corr_offset = [(ypeak-size(template,1)) (xpeak-size(template,2))];isequal(corr_offset,offset)
ans = logical 1

Input Arguments

collapse all

a, bInput arrays
matrices

Input arrays, specified as matrices.

Example: sin(2*pi*(0:9)'/10)*sin(2*pi*(0:13)/20) specifies a two-dimensional sinusoidal surface.

Data Types: single | double
Complex Number Support: Yes

Output Arguments

collapse all

c — 2-D cross-correlation or autocorrelation matrix
matrix

2-D cross-correlation or autocorrelation matrix, returned as a matrix.

More About

collapse all

2-D Cross-Correlation

The 2-D cross-correlation of an M-by-N matrix, X, and a P-by-Q matrix, H, is a matrix, C, of size M+P–1 by N+Q–1. Its elements are given by

C(k,l)=m=0M1n=0N1X(m,n)H¯(mk,nl),(P1)kM1,(Q1)lN1,

where the bar over H denotes complex conjugation.

The output matrix, C(k,l), has negative and positive row and column indices.

  • A negative row index corresponds to an upward shift of the rows of H.

  • A negative column index corresponds to a leftward shift of the columns of H.

  • A positive row index corresponds to a downward shift of the rows of H.

  • A positive column index corresponds to a rightward shift of the columns of H.

To cast the indices in MATLAB® form, add the size of H: the element C(k,l) corresponds to C(k+P,l+Q) in the workspace.

For example, consider this 2-D cross-correlation:

X = ones(2,3);H = [1 2; 3 4; 5 6]; % H is 3 by 2C = xcorr2(X,H)
C = 6 11 11 5 10 18 18 8 6 10 10 4 2 3 3 1

The C(1,1) element in the output corresponds to C(1–3,1–2)=C(–2,–1) in the defining equation, which uses zero-based indexing. To compute the C(1,1) element, shift H two rows up and one column to the left. Accordingly, the only product in the cross-correlation sum is X(1,1)*H(3,2) = 6. Using the defining equation, you obtain

C(2,1)=m=01n=02X(m,n)H¯(m+2,n+1)=X(0,0)H¯(2,1)=1×6=6,

with all other terms in the double sum equal to zero.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

This function fully supports GPU arrays. For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Version History

Introduced before R2006a

See Also

conv2 | filter2 | xcorr

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

2-D cross-correlation - MATLAB xcorr2 (7)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

2-D cross-correlation - MATLAB xcorr2 (2024)

FAQs

How do you find the cross-correlation of two sequences in Matlab? ›

r = xcorr( x , y ) returns the cross-correlation of two discrete-time sequences. Cross-correlation measures the similarity between a vector x and shifted (lagged) copies of a vector y as a function of the lag.

What is the function of xcorr2 in Matlab? ›

Description. c = xcorr2( a , b ) returns the cross-correlation of matrices a and b with no scaling. xcorr2 is the two-dimensional version of xcorr . c = xcorr2( a ) is the autocorrelation matrix of input matrix a .

What is the difference between Xcorr and Crosscorr in Matlab? ›

The difference is that xcorr in the Signal Processing toolbox allows the user to specify some normalization method, but this is not the case for crosscor. The basic definition of both the commands are: 1) r = xcorr(x,y) returns the cross-correlation of two discrete-time sequence.

How do you find the correlation between two variables in Matlab? ›

Description. R = corrcoef( A ) returns the matrix of correlation coefficients for A , where the columns of A represent random variables and the rows represent observations. R = corrcoef( A , B ) returns coefficients between two random variables A and B .

What is the cross-correlation between two sequences? ›

Cross-correlation is defined as a measure of the similarity between two waveforms based on their relative delay. It is commonly used in seismic data processing to compare sampled sequences of signals for geophysical analysis.

How to calculate cross-correlation? ›

The cross-correlation of a pair of jointly wide sense stationary stochastic processes can be estimated by averaging the product of samples measured from one process and samples measured from the other (and its time shifts).

How to interpret cross-correlation? ›

Interpretation. Use the cross correlation function to determine whether there is a relationship between two time series. To determine whether a relationship exists between the two series, look for a large correlation, with the correlations on both sides that quickly become non-significant.

What is the difference between cross-correlation and correlation? ›

Correlation defines the degree of similarity between two indicates. If the indicates are alike, then the correlation coefficient will be 1 and if they are entirely different then the correlation coefficient will be 0. When two independent indicates are compared, this procedure will be called as cross-correlation.

What is normalized cross-correlation coefficient in MATLAB? ›

Normalized cross-correlation is an undefined operation in regions where A has zero variance over the full extent of the template. In these regions, normxcorr2 assigns correlation coefficients of zero to the output C .

What is normalized cross-correlation? ›

Normalized cross correlation (NCC) is a metric that measures the linear association between two variables by eliminating the dependency on the amplitude of the signals being compared.

What is the difference between conv and Xcorr? ›

In signal / image processing, convolution is defined as it is defined as the integral of the product of the two functions after one is reversed and shifted. On the other hand, cross-correlation is known as sliding dot product or sliding inner-product of two functions. The filter in cross-correlation is not reversed.

What is cross in MATLAB? ›

C = cross( A,B ) returns the cross product of A and B . If A and B are vectors, then they must have a length of 3. If A and B are matrices or multidimensional arrays, then they must have the same size. In this case, the cross function treats A and B as collections of three-element vectors.

What is the difference between Corr and Corrcoef in Matlab? ›

The difference between corr(X,Y) and the MATLAB® function corrcoef(X,Y) is that corrcoef(X,Y) returns a matrix of correlation coefficients for two column vectors X and Y . If X and Y are not column vectors, corrcoef(X,Y) converts them to column vectors.

Which is the best way to show 2 correlation between variables? ›

The basic practice of statistics (6th ed.). New York, NY: W. H. Freeman and Company. The most useful graph for displaying the relationship between two quantitative variables is a scatterplot.

What is the cross-correlation technique? ›

Cross-correlation is used to track the similarities in the movement of two factors or potential investments over time. Stock investors use it to determine the degree to which two stocks move in tandem.

What is the Corr method in Matlab? ›

Description. rho = corr( X ) returns a matrix of the pairwise linear correlation coefficient between each pair of columns in the input matrix X . rho = corr( X , Y ) returns a matrix of the pairwise correlation coefficient between each pair of columns in the input matrices X and Y .

What is the function of Corrmtx in Matlab? ›

Description. H = corrmtx( x , m ) returns an (n+ m )-by-( m +1) rectangular Toeplitz matrix H = H such that HH is a biased estimate of the autocorrelation matrix for the input vector x . n is the length of x , m is the prediction model order, and H is the conjugate transpose of H.

What is the cross product of two vectors in Matlab? ›

C = cross( A,B ) returns the cross product of A and B . If A and B are vectors, then they must have a length of 3. If A and B are matrices or multidimensional arrays, then they must have the same size. In this case, the cross function treats A and B as collections of three-element vectors.

How do you show correlation in Matlab? ›

[ R , PValue ] = corrplot( Tbl ) plots the Pearson's correlation coefficients between all pairs of variables in the input table or timetable, and also returns tables for the correlation matrix and matrix of p-values.

Top Articles
Vortex Support added: X4: Foundations, Pathfinder: Kingmaker, Starsector, 7 Days to Die
Vortex Support added: X4: Foundations, Pathfinder: Kingmaker, Starsector, 7 Days to Die
Mickey Moniak Walk Up Song
NOAA: National Oceanic & Atmospheric Administration hiring NOAA Commissioned Officer: Inter-Service Transfer in Spokane Valley, WA | LinkedIn
Canya 7 Drawer Dresser
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Jazmen Jafar Linkedin
Unlocking the Enigmatic Tonicamille: A Journey from Small Town to Social Media Stardom
The Pope's Exorcist Showtimes Near Cinemark Hollywood Movies 20
The Powers Below Drop Rate
What is international trade and explain its types?
Joe Gorga Zodiac Sign
Unit 1 Lesson 5 Practice Problems Answer Key
Signs Of a Troubled TIPM
4302024447
今月のSpotify Japanese Hip Hopベスト作品 -2024/08-|K.EG
Fairy Liquid Near Me
Tracking Your Shipments with Maher Terminal
Ostateillustrated Com Message Boards
Char-Em Isd
Epguides Strange New Worlds
Reptile Expo Fayetteville Nc
Sherburne Refuge Bulldogs
Synergy Grand Rapids Public Schools
Tire Plus Hunters Creek
Idle Skilling Ascension
Table To Formula Calculator
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
They Cloned Tyrone Showtimes Near Showbiz Cinemas - Kingwood
Pdx Weather Noaa
Davita Salary
Kaiserhrconnect
Fridley Tsa Precheck
Netherforged Lavaproof Boots
Chattanooga Booking Report
All Things Algebra Unit 3 Homework 2 Answer Key
School Tool / School Tool Parent Portal
Wrigley Rooftops Promo Code
303-615-0055
Questions answered? Ducks say so in rivalry rout
Craigslist Odessa Midland Texas
Clausen's Car Wash
Jaefeetz
Yale College Confidential 2027
Youravon Com Mi Cuenta
3500 Orchard Place
Worland Wy Directions
Underground Weather Tropical
Rovert Wrestling
David Turner Evangelist Net Worth
Latest Posts
Article information

Author: Golda Nolan II

Last Updated:

Views: 5966

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.