Is vectorizing this even possible?

1 view (last 30 days)
vec3(1) = 1;
i = 1;
while i<5
i = i+1;
vec3(i) = (vec3(i-1)+2)^2;
end
vec3

Accepted Answer

Walter Roberson
Walter Roberson on 17 Sep 2020
I posted the complete vectorization several days ago; . Unfortunately the person deleted the question.
syms v v0 c
f(v) = (v+c)^2;
f5 = f(f(f(f(f(v0)))));
vec3_5 = expand(subs(f5, c, 2));
v0^32 + 64*v0^31 + 2016*v0^30 + 41600*v0^29 + 631536*v0^28 + 7511168*v0^27 + 72782528*v0^26 + 590011136*v0^25 + 4077667064*v0^24 + 24363708032*v0^23 + 127184607424*v0^22 + 584772138240*v0^21 + 2382767071968*v0^20 + 8644745151232*v0^19 + 28021844462720*v0^18 + 81349497514496*v0^17 + 211814884610908*v0^16 + 494935571753856*v0^15 + 1037540400943680*v0^14 + 1949025086827264*v0^13 + 3273934344609568*v0^12 + 4902203714779904*v0^11 + 6514485357242496*v0^10 + 7638211784159744*v0^9 + 7840967227104336*v0^8 + 6975721989473536*v0^7 + 5305860461727104*v0^6 + 3387252771621376*v0^5 + 1768336935606208*v0^4 + 726328276999680*v0^3 + 220554340195584*v0^2 + 44118436709376*v0 + 4371938082724
Where v0 = 1
  3 Comments
Walter Roberson
Walter Roberson on 18 Sep 2020
Yup ;-)
Using a for loop is not vectorizing . This solution is not vectorized in terms of the number of iterations, but it is vectorized in terms of different initial conditions.
I think it should be possible to calculate what all the terms should be, in terms of binomial coefficients and number of iterations, but the form is not coming to mind immediately.

Sign in to comment.

More Answers (1)

madhan ravi
madhan ravi on 17 Sep 2020
Edited: madhan ravi on 17 Sep 2020
A simple for loop is the best and easier to understand:
vec3 = zeros(5,1);
vec3(1) = 1;
for k = 2:5 % edited after Stephen’s comment
vec3(k) = (vec3(k-1)+2)^2;
end
vec3
  2 Comments
Stephen23
Stephen23 on 17 Sep 2020
Starting the for loop from one will throw an error. Better to start from two:
vec3 = ones(5,1);
for k = 2:5
vec3(k) = (vec3(k-1)+2)^2;
end

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!