How can I simplify/vectorize this nested loop version of pascals triangle?

5 次查看(过去 30 天)
%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

采纳的回答

OCDER
OCDER 2018-6-12
  2 个评论
Mark Nelson
Mark Nelson 2018-6-12
@OCDER obviously not what I'm looking for. Perhaps there is no easier way. Thanks anyway.
OCDER
OCDER 2018-6-12
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by