Matrix with alternating signs in each row vector

조회 수: 2 (최근 30일)
Leor Greenberger
Leor Greenberger 2011년 9월 19일
댓글: the cyclist 2014년 8월 13일
Hi Guys,
Is there a way to improve on this code that I wrote to optimize it?
M = zeros(M,N); % create an MxN matrix
M(1,:) = 1; % Set first row to 1
for r = 2:I
M(r,:) = -M(r-1,:); %sets alternate rows to -1 and +1
end
a = M * diag(1 2 3 4 5);
so M creates:
M =
1 1 1 1 1
-1 -1 -1 -1 -1
1 1 1 1 1
-1 -1 -1 -1 -1
1 1 1 1 1
-1 -1 -1 -1 -1
1 1 1 1 1
-1 -1 -1 -1 -1
and a
a =
1 2 3 4 5
-1 -2 -3 -4 -5
1 2 3 4 5
-1 -2 -3 -4 -5
1 2 3 4 5
-1 -2 -3 -4 -5
1 2 3 4 5
-1 -2 -3 -4 -5
Is this the fastest and most efficient implementation to get the above? Thanks!

채택된 답변

Fangjun Jiang
Fangjun Jiang 2011년 9월 19일
Some improvement.
m=5;n=4;
M=ones(m,n);
M(2:2:end,:)=-1
Or alternative:
m=9;n=8;
a=(2*mod((1:m)',2)-1)*(1:n)
  댓글 수: 5
the cyclist
the cyclist 2011년 9월 19일
I suggest that accept one of the answers here, assuming that it helped you. And make this comment into a separate question.
Fangjun Jiang
Fangjun Jiang 2011년 9월 19일
For that, you can use repmat.
b=repmat(k',1,N)+a

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

추가 답변 (3개)

the cyclist
the cyclist 2011년 9월 19일
One of many ways to get your result:
M = 7;
N = 5;
V = (-1).^(0:M);
A = bsxfun(@times,1:N,V')
  댓글 수: 3
Jan
Jan 2011년 9월 20일
The power operation is very expensive. Using MOD is much faster.
Andrei Bobrov
Andrei Bobrov 2011년 9월 20일
Hi Jan! My "research"
>> t = zeros(100,2);
for j1 = 1:100
tic,(-1).^(0:1000)'*(1:100);t(j1,1)=toc;
tic,(2*rem((1:1000)',2)-1)*(1:100);t(j1,2)=toc;
end
>> [min(t);mean(t);median(t);max(t)]
ans =
0.0008 0.0006
0.0012 0.0012
0.0012 0.0010
0.0030 0.0259

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


Sean de Wolski
Sean de Wolski 2011년 9월 19일
b = bsxfun(@plus,k',a(:,1:N))
to your comment in the Fangjun's answer.

Jonathan
Jonathan 2014년 8월 13일
is there a generic way of making an array of ones that alternate form +1 to -1?
  댓글 수: 1
the cyclist
the cyclist 2014년 8월 13일
Why did you bury a brand-new question as a comment on a 3-year-old thread?

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by