フィルターのクリア

Creating a matrix that is more time efficient

1 回表示 (過去 30 日間)
Nicholas Ootani
Nicholas Ootani 2018 年 3 月 16 日
コメント済み: Nicholas Ootani 2018 年 3 月 17 日
Hey guys,
My problem is as follows.
I want to create a matrix that has certain logic like so.
% code
n = 50; % Just an arbitrary number
B = rand(1,n);
A = rand(1,n);
% The components of the vectors A and B are not necessary a number between 0 and 1. But a calculated number, but for the purpose of this problem I'd rather use this random generated vector.
for i = 1:n
for j = 1:n
if i == j
C(i, j) = 5*B(1, i) + A(1,j);
else
C(i, j) = -B(1, i) + 3*A(1, j);
end
end
end
The code up above does the works, but it takes quite a long time, since it makes each component individually.
So my question is, is there a more efficient way to create this matrix?

採用された回答

James Tursa
James Tursa 2018 年 3 月 16 日
編集済み: James Tursa 2018 年 3 月 16 日
C = 3*A - B(:); % or C = bsxfun(@minus,3*A,B(:))
C(1:n+1:end) = 5*B + A;
  7 件のコメント
James Tursa
James Tursa 2018 年 3 月 17 日
The bsxfun( ) version:
N = 1:n;
% D = sin(A)./((cos(A)-cos(A(:))).^2).*(((1-(-1).^(N-N(:)))/(2*(n+1))));
cosA = cos(A);
sinA = sin(A);
costemp = bsxfun(@minus,cosA,cosA(:));
sincostemp = bsxfun(@rdivide,sinA,costemp.^2);
Ntemp = bsxfun(@minus,N,N(:));
D = sincostemp.*(((1-(-1).^Ntemp)/(2*(n+1))));
D(1:n+1:end) = -((n+1)./(4*sinA)+B);
Nicholas Ootani
Nicholas Ootani 2018 年 3 月 17 日
It worked, man, you are awesome.
Never thought that you could use bsxfun() like that.
once more, thanks, problem solved

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by