Creating a matrix that is more time efficient
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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
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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!