필터 지우기
필터 지우기

How to improve a for

조회 수: 3 (최근 30일)
Carlos
Carlos 2014년 10월 11일
편집: Andrei Bobrov 2014년 10월 11일
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.

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 10월 11일

추가 답변 (2개)

Jan
Jan 2014년 10월 11일
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
Carlos
Carlos 2014년 10월 11일
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 2014년 10월 11일
Yes, Carlos.

댓글을 달려면 로그인하십시오.


Andrei Bobrov
Andrei Bobrov 2014년 10월 11일
편집: Andrei Bobrov 2014년 10월 11일
f = -dot(Q,Q).'

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by