필터 지우기
필터 지우기

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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by