How to improve a for

1 visualización (últimos 30 días)
Carlos
Carlos el 11 de Oct. de 2014
Editada: Andrei Bobrov el 11 de Oct. de 2014
Hello, i want to do this operation:
f = -[Q(:,1)'*Q(:,1); Q(:,2)'*Q(:,2); Q(:,3)'*Q(:,3); Q(:,4)'*Q(:,4); Q(:,5)'*Q(:,5); Q(:,6)'*Q(:,6); Q(:,7)'*Q(:,7); Q(:,8)'*Q(:,8); Q(:,9)'*Q(:,9); Q(:,10)'*Q(:,10)];
i have thought to do this with a for
n=10;
i=1;
while i<n+1
f(i,1)=-[Q(:,i)'*Q(:,i)]; %save in columns
i=i+1;
end
but i think there must be some way to vectorize this easily. Could you help me?
Thank you.

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 11 de Oct. de 2014

Más respuestas (2)

Jan
Jan el 11 de Oct. de 2014
The vectorization is better, but here is a cleaner and more efficient loop method:
f = zeros(10, 1); % pre-allocate!!!
for k = 1:10
f(k, 1) = -(Q(:,k)' * Q(:,k));
end
  2 comentarios
Carlos
Carlos el 11 de Oct. de 2014
Thank you so much. I think that the for loop is much better than mine before. Otherwise, how is the way to make the vectorization? Is it the answer of Azzi?
Jan
Jan el 11 de Oct. de 2014
Yes, Carlos.

Iniciar sesión para comentar.


Andrei Bobrov
Andrei Bobrov el 11 de Oct. de 2014
Editada: Andrei Bobrov el 11 de Oct. de 2014
f = -dot(Q,Q).'

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by