How to create a (nxn) matrix with alternating sign

How do i create a (n x n) matrix whose elements are either +3 or –3 such that the sign of each element is different from its adjacent elements, both from those above and below it and from those on either side of it (see Y below).

Answers (5)

Just for fun, here's how it can be done with loops
n=3; %value chosen
r=3; %number of rows
c=3; %number of columns
m=zeros(r,c); %pre-allocate output
for cc=1:c %do it for all columns
for rr=1:r %do it for all rows
m(rr,cc)=n*(-1)^(rr+cc); %put the value in the place
end
end
m %the output

2 Comments

+1 The only single solution offered as of now which works for both even and odd n.
Ouch. Indeed. I take my solution back.

Sign in to comment.

Here is another which works for even or odd n.
M = toeplitz((-1).^(1:n));
And even faster (very much so for large n!)...
M = (-1).^(1:n);
M = 3*M.'*M
Note that this can be generalized, like Paulo's solution, to m-by-n.
M = 3*((-1).^(1:m).')*((-1).^(1:n))
EDIT .
.
What is surprising to me is that this is even faster than the above for large m,n:
M = zeros(m,n);
M(:,1) = 3*((-1).^(0:m-1).');
for ii = 2:n
M(:,ii) = (-1)^(ii+1)*M(:,1);
end

2 Comments

You won the fastest-to-the-button this time!
"1-2*rem(x, 2)" is faster than "(-1)^x".

Sign in to comment.

b =
-3 3
3 -3
b=repmat(b,3,3)
b =
-3 3 -3 3 -3 3
3 -3 3 -3 3 -3
-3 3 -3 3 -3 3
3 -3 3 -3 3 -3
-3 3 -3 3 -3 3
3 -3 3 -3 3 -3

2 Comments

I want to have the user specify n and do this with a for loop i think.

Sign in to comment.

For odd n
m = 3 * ones(n);
m(1:end) = m(1:end) .* (-1).^(1:numel(m));
Or, for even n,
m = kron(3 * ones(n/2), [-1 1;1 -1]);
%And a BSXFUN solution
n = 3;
r = 4;
c = 5;
m = bsxfun(@(x,y)n*(-1).^(x+y),(1:r).',1:c)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 11 Apr 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!