iteration with for for a simple computation

조회 수: 1 (최근 30일)
Paul Rogers
Paul Rogers 2020년 7월 8일
댓글: Paul Rogers 2020년 7월 8일
I'd like do write this expression in a more compact and generic way, like with a for:
T = c(1)*cos(0) + c(2).*cos(1.*acos((m))) + c(3).*cos(2.*acos((m))) + c(4).*cos(3.*acos((m))) + ...
c(5).*cos(4.*acos((m)));
where the vector m and c are in attached.

채택된 답변

dpb
dpb 2020년 7월 8일
One way amongst many...
z=acos(m); % precompute the constant array
T=c(1)+sum(cell2mat(arrayfun(@(c,i) c*cos(i*z),c(2:end),[1:numel(c)-1].','UniformOutput',false)));
The straight for...end loop might be quicker and probably easier to read.
I don't know if the JIT optimizer can find and eliminate the redundant calculation of acos(m) on its own or not; didn't try any timing tests...
  댓글 수: 1
Paul Rogers
Paul Rogers 2020년 7월 8일
brilliant, thank you a lot, it's a solution I would have never tought!

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

추가 답변 (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