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).

답변 (5개)

Paulo Silva
Paulo Silva 2011년 4월 11일

2 개 추천

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

Matt Fig
Matt Fig 2011년 4월 11일
+1 The only single solution offered as of now which works for both even and odd n.
Ouch. Indeed. I take my solution back.

댓글을 달려면 로그인하십시오.

Matt Fig
Matt Fig 2011년 4월 11일

1 개 추천

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

You won the fastest-to-the-button this time!
Jan
Jan 2011년 5월 13일
"1-2*rem(x, 2)" is faster than "(-1)^x".

댓글을 달려면 로그인하십시오.

bym
bym 2011년 4월 11일

0 개 추천

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

Patrick
Patrick 2011년 4월 11일
I want to have the user specify n and do this with a for loop i think.
Why a for loop?

댓글을 달려면 로그인하십시오.

Walter Roberson
Walter Roberson 2011년 4월 11일

0 개 추천

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
Sean de Wolski 2011년 4월 11일

0 개 추천

%And a BSXFUN solution
n = 3;
r = 4;
c = 5;
m = bsxfun(@(x,y)n*(-1).^(x+y),(1:r).',1:c)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2011년 4월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by