Printing pascals triangle binomial in loop
조회 수: 20 (최근 30일)
이전 댓글 표시
n = input('n:');
%Create first two rows that are always constant
pt(1, 1) = 1;
pt(2, 1 : 2) = [1 1];
for row = 3 : n
% First element of every row
pt(row, 1) = 1;
% Every element is the addition of the two elements
% on top of it. That means the previous row.
for column = 2 : row-1
pt(row, column) = pt(row-1, column-1) + pt(row-1, column);
end
% Last element of every row
pt(row, row) = 1;
end
I have created the pascals triangle but I am trying to print the polynomial expansion of the value n. ie fprintf('(x+y)^3= x^3+3x^2y+x3xy^2+y^3');
the isuue is the value of n keeps on changing based on user input. Is there a way to create loop for such printing.
댓글 수: 0
채택된 답변
John D'Errico
2020년 3월 13일
Well, you have made a reasonable start, and all you really need is to find a way to output what you have done.
The conv trick here is a nice way to encapsulate the multiplies. It is a nice trick to learn for the future.
% preallocate the array of binomial polynomial coefficients
Pcoef = cell(n+1,1);
% the zero'th order polynomial is just 1 of course
Pcoef{1} = 1;
for m = 1:n
% see that conv does what is effectively the multiplication you need.
Pcoef{m+1} = conv(Pcoef{m},[1 1]);
end
% now build the desired polynomial as output
% we always know the first and last terms, and
% the second and penultimate terms are subtly different.
Pfinal = ['x^',int2str(n)'];
for m = 2:n
if m == 2
Pfinal = [Pfinal,' + ',int2str(Pcoef{end}(m)),'*x^',int2str(n-m+1),'*y'];
elseif m == n
Pfinal = [Pfinal,' + ',int2str(Pcoef{end}(m)),'*x*y^',int2str(m-1)];
else
Pfinal = [Pfinal,' + ',int2str(Pcoef{end}(m)),'*x^',int2str(n-m+1),'*y^',int2str(m-1)];
end
end
Pfinal = [Pfinal,' + 1'];
disp(Pfinal)
For example, with n = 5, we see
x^5 + 5*x^4*y + 10*x^3*y^2 + 10*x^2*y^3 + 5*x*y^4 + 1
The Pascal's triangle produced was:
Pcoef{:}
ans =
1
ans =
1 1
ans =
1 2 1
ans =
1 3 3 1
ans =
1 4 6 4 1
ans =
1 5 10 10 5 1
댓글 수: 4
Alexander Ljubenkovic-Shah
2021년 2월 18일
DUDE! YOUR SCRIPT FAILS MISERABLY AS SOON AS THE POWER INPUT IS A 2-DIGIT NUMBER! YOUR SCRIPT CAN ONLY DO POWERS UP TO 9. HOW DO YOU FIX THAT?
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!