How can I simplify/vectorize this nested loop version of pascals triangle?
4 views (last 30 days)
Show older comments
%mypascal
n = input('Enter a value for n: ');
% create matrix using nested loops (programming method)
somemat = ones(n);
for i = 2:n
for j = 2:n
somemat(i,j) = somemat(i-1,j) + somemat(i, j-1);
end
end
2 Comments
Accepted Answer
OCDER
on 12 Jun 2018
2 Comments
OCDER
on 12 Jun 2018
Yeah, I don't think you can vectorize it completely, otherwise Mathwork's pascal would have shown the vectorized code. Since the pascal triangle is symmetric, you could vectorize the filling of the other half of the triangle, which will speed up the code.
For n = 2000, pascal.m is ~ 5 times faster than your pure for loop approach.
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!