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

%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

@Mark Nelson: is there a specific problem with using a loop?
No, I'm just wondering if there is a built in function (like meshgrid) that will do it in one step.

댓글을 달려면 로그인하십시오.

 채택된 답변

OCDER
OCDER 2018년 6월 12일
Behold, a function called pascal
S = pascal(n)

댓글 수: 2

@OCDER obviously not what I'm looking for. Perhaps there is no easier way. Thanks anyway.
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개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2018년 6월 12일

댓글:

2018년 6월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by