Is vectorizing this even possible?
Show older comments
vec3(1) = 1;
i = 1;
while i<5
i = i+1;
vec3(i) = (vec3(i-1)+2)^2;
end
vec3
Accepted Answer
More Answers (1)
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
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
madhan ravi
on 17 Sep 2020
Ah thanks Stephen!
Categories
Find more on Programming 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!