Borrar filtros
Borrar filtros

Creating a matrix that is more time efficient

1 visualización (últimos 30 días)
Nicholas Ootani
Nicholas Ootani el 16 de Mzo. de 2018
Comentada: Nicholas Ootani el 17 de Mzo. de 2018
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?

Respuesta aceptada

James Tursa
James Tursa el 16 de Mzo. de 2018
Editada: James Tursa el 16 de Mzo. de 2018
C = 3*A - B(:); % or C = bsxfun(@minus,3*A,B(:))
C(1:n+1:end) = 5*B + A;
  7 comentarios
James Tursa
James Tursa el 17 de Mzo. de 2018
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 el 17 de Mzo. de 2018
It worked, man, you are awesome.
Never thought that you could use bsxfun() like that.
once more, thanks, problem solved

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by