Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix of alternating 1 and -1 elements - MATLAB

Tags:

matrix

matlab

I'd like to know how to create a matrix n x n the following order, for example

n=3;

 1 -1  1     
-1  1 -1
 1 -1  1

n=4;

 1 -1  1 -1
-1  1 -1  1
 1 -1  1 -1
-1  1 -1  1

for every number n.

like image 856
el11 Avatar asked Nov 30 '22 11:11

el11


2 Answers

Another way is to produce a meshgrid of points, then calculate:

(-1)^(x+y)  ,

where x and y are the 2D co-ordinate positions inside the grid. The main intuition behind this approach is when you take -1 and power it to an odd number, you return -1, and if it's an even number, it's +1. By taking a look at each location in a 2D grid, the parity (odd/even-ness) when you sum the (x,y) co-ordinates together alternates between odd and even... assuming integer co-ordinates of course. You can take advantage of this by taking the sum of each (x,y) location, and applying this to the power coefficient with -1 as the base to achieve our alternating matrix you desire.

I was inspired by this approach by considering how the determinant of a matrix is calculated. Check out Laplace's formula on calculating the determinant here: http://en.wikipedia.org/wiki/Determinant#Laplace.27s_formula_and_the_adjugate_matrix

As such:

n = 3; %// Define n here
[X,Y] = meshgrid(1:n, 1:n);
A = (-1).^(X+Y)

A =

     1    -1     1
    -1     1    -1
     1    -1     1

If you want to show this for n = 4:

A =

     1    -1     1    -1
    -1     1    -1     1
     1    -1     1    -1
    -1     1    -1     1
like image 140
rayryeng Avatar answered Dec 04 '22 11:12

rayryeng


This solution involves no arithmetic operations:

A = ones(n);
A(1:2:end, 2:2:end) = -1;
A(2:2:end, 1:2:end) = -1;
like image 29
Luis Mendo Avatar answered Dec 04 '22 12:12

Luis Mendo