Eliminate for-loop in recursive computation?
6 views (last 30 days)
Show older comments
Christopher Smith
on 28 Jan 2025
Commented: Christopher Smith
on 29 Jan 2025
I'm trying to speed up a recursive calculation that is currently using a for-loop. A minimum working example is below. There are two computations in the recursion: "pn0" and "fact". I have figured out how to do fact out side the loop, but pn0 is giving me trouble. Any insight into how to remove the loop and/or speed this up would be greatly appreaciated! I have tried building up a separate function and using arrayfun, but that is calling a loop under the hood, so I don't think it would be faster.
% define some constants
m = 0:10;
y = cos(pi/4);
% compute fact without a loop
fact = cumsum([1 ones(1,size(m,2)).*2]);
fact = fact(1:end-1);
% Generate the correct pn0 array
pn0 = 1; % initial value
factdum = 1; % initial value
pn_out = [];
fact_out = [];
for mm = 0:10
pn0 = -pn0*factdum*y; % do the computation <-- this is the computation I'm trying to pull out of the loop
pn_out = [pn_out,pn0]; % store the pn0 array output
fact_out = [fact_out,factdum]; % store the fact array output
factdum = factdum + 2; % compute fact inside the loop to make sure it was done correctly outside the loop.
end
0 Comments
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!