How to create a (nxn) matrix with alternating sign
Show older comments
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)
Paulo Silva
on 11 Apr 2011
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
Matt Fig
on 11 Apr 2011
+1 The only single solution offered as of now which works for both even and odd n.
Teja Muppirala
on 11 Apr 2011
Ouch. Indeed. I take my solution back.
Matt Fig
on 11 Apr 2011
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
Walter Roberson
on 11 Apr 2011
You won the fastest-to-the-button this time!
Jan
on 13 May 2011
"1-2*rem(x, 2)" is faster than "(-1)^x".
bym
on 11 Apr 2011
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
Walter Roberson
on 11 Apr 2011
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]);
Sean de Wolski
on 11 Apr 2011
%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
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!