better method for evaluating matrix

3 ビュー (過去 30 日間)
JaeSung Choi
JaeSung Choi 2017 年 11 月 21 日
編集済み: Stephen23 2017 年 11 月 21 日
For given vector such as following, I want to make square matrix s such that
%constant, original form
N = 500;
x = 2*pi*linspace(0,1,N);
for i = 1:N
for j = 1:N
s(i,j) = sin(x(i)-x(j))
end
end
But it was too slow, so recently I edited it to following, but it's still too slow!!
Can anybody please help me??
%constant
N = 500;
x = 2*pi*linspace(0,1,N);
for i = 1: N;
s(:,i) = x-x(i);
end
s=sin(s);

採用された回答

Stephen23
Stephen23 2017 年 11 月 21 日
編集済み: Stephen23 2017 年 11 月 21 日
You really need to learn how to write vectorized code. Solving every task using lots of ugly loops is not an efficient way to write MATLAB code. Try this:
N = 500;
vec = 2*pi*linspace(0,1,N);
mat = sin(bsxfun(@minus,vec(:),vec))

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 11 月 21 日
編集済み: Andrei Bobrov 2017 年 11 月 21 日
N = 500;
x = 2*pi*linspace(0,1,N);
s = sin(x(:)' - x(:));
for old versions of MATLAB:
s = sin( bsxfun(@minus, x(:)',x(:)) );
  1 件のコメント
Stephen23
Stephen23 2017 年 11 月 21 日
編集済み: Stephen23 2017 年 11 月 21 日
Note that the output is transposed compared to the code given in the question.

サインインしてコメントする。

カテゴリ

Help Center および File Exchange시작과 종료 についてさらに検索

Community Treasure Hunt

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

Start Hunting!