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

7 Ansichten (letzte 30 Tage)
%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 Kommentare
Stephen23
Stephen23 am 12 Jun. 2018
@Mark Nelson: is there a specific problem with using a loop?
Mark Nelson
Mark Nelson am 12 Jun. 2018
No, I'm just wondering if there is a built in function (like meshgrid) that will do it in one step.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by