Matrix with alternating signs in each row vector
古いコメントを表示
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!
採用された回答
その他の回答 (3 件)
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 件のコメント
Andrei Bobrov
2011 年 9 月 20 日
(-1).^(0:7)'*(1:5)
Jan
2011 年 9 月 20 日
The power operation is very expensive. Using MOD is much faster.
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
2011 年 9 月 19 日
b = bsxfun(@plus,k',a(:,1:N))
to your comment in the Fangjun's answer.
Jonathan
2014 年 8 月 13 日
0 投票
is there a generic way of making an array of ones that alternate form +1 to -1?
1 件のコメント
the cyclist
2014 年 8 月 13 日
Why did you bury a brand-new question as a comment on a 3-year-old thread?
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!