필터 지우기
필터 지우기

How to speed up for loop with a few calculations?

조회 수: 1 (최근 30일)
Dawid Smolen
Dawid Smolen 2016년 6월 15일
댓글: Dawid Smolen 2016년 6월 15일
My question is how to speed up for loop with a number of different calculations, such as abs, multiplication, sqrt, ^2, cos(), and array indexing? (there is array(i) )
for i=ind1:ind2
A = ( array(i)*(i+ind2) + array(i)*(i+ind1) ) / sqrt((ind2-i)^2 + (ind1-i)^2);
A = cos(pi*A);
% and so on
end
Is it possible to use some really complicated bsxfun(), repmat()? I am not looking for exact solution, just would like to know if it is possible, when, and which functions might be helpful

채택된 답변

Guillaume
Guillaume 2016년 6월 15일
Your question is far too generic to be able to give a precise answer.
The first mistake people do is operate on an array one element at a time instead of operating on the whole array at once. Other than the fact that you constantly overwrite A, this appears to be the mistake you've made in your example.
%assuming array is a row vector
v = ind1:ind2; %make a vector of the values i iterates over
A = (array .* (v + ind2) + array .*(v + ind1)) ./ hypot(ind2 - v, ind1 - v);
A = cos(pi*A);
Note the use of .* and ./ for elementwise operation. See array vs matrix operations.
For more complicated stuff, bsxfun, repmat, ndgrid, etc. may be useful indeed.
  댓글 수: 1
Dawid Smolen
Dawid Smolen 2016년 6월 15일
Although the question was general, you have helped me. Now it seems like basics, but because of the complicated math, I was confused and couldn't think of simple solution. Thank you

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by