Printing pascals triangle binomial in loop
6 ビュー (過去 30 日間)
古いコメントを表示
Pallav Patel
2020 年 3 月 13 日
コメント済み: Alexander Ljubenkovic-Shah
2021 年 2 月 18 日
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 で Arithmetic Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!