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
.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With