Printing pascals triangle binomial in loop

6 次查看(过去 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.

采纳的回答

John D'Errico
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 个评论
Pallav Patel
Pallav Patel 2020-3-13
Thank you. This is way much better. It is because I still don't understand cells as it is two subtopics away and that is why the first one didn't work for me.
Alexander Ljubenkovic-Shah
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 CenterFile Exchange 中查找有关 Arithmetic Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by