Borrar filtros
Borrar filtros

Printing pascals triangle binomial in loop

6 visualizaciones (últimos 30 días)
Pallav Patel
Pallav Patel el 13 de Mzo. de 2020
Comentada: Alexander Ljubenkovic-Shah el 18 de Feb. de 2021
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.

Respuesta aceptada

John D'Errico
John D'Errico el 13 de Mzo. de 2020
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 comentarios
Pallav Patel
Pallav Patel el 13 de Mzo. de 2020
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
Alexander Ljubenkovic-Shah el 18 de Feb. de 2021
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?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Arithmetic Operations en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by