Vincent Cheung

Vincent Cheung's Blog

« Newer Post Home Older Post »

Monday, July 19, 2004

Indexing in a circularly wrapped matrix in Matlab

Neat trick in Matlab to index a matrix in a circularly wrapped manner (eg. with image / video epitomes). Also generally useful for indexing into matrices.

The key idea is to use vectors to index into the matrix. This is made easier with cells (especially when dealing with multidimensional arrays).

Take this example:

>> a = pascal(6)

a =

1 1 1 1 1 1
1 2 3 4 5 6
1 3 6 10 15 21
1 4 10 20 35 56
1 5 15 35 70 126
1 6 21 56 126 252

>> b = magic(4)

b =

16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

>> subs = {mod(4:7, 6)+1, mod(4:7, 6)+1}; subs{:}

ans =

5 6 1 2


ans =

5 6 1 2

>> a(subs{:})

ans =

70 126 1 5
126 252 1 6
1 1 1 1
5 6 1 2

>> a(subs{:}) = b

a =

6 12 1 1 9 7
15 1 3 4 4 14
1 3 6 10 15 21
1 4 10 20 35 56
3 13 15 35 16 2
10 8 21 56 5 11


Executive summary: took a 4x4 circularly wrapped patch in "a" and replaced with "b" and the indexing was made cleaner with the use of a cell


You could also just simply do the following:
a([5 6 1 2], [5 6 1 2]) = b

but using the cell gives you more flexibility when using this in "real" situations where you probably have to do this a number of times.

0 Comments:

Post a Comment