MATLAB: Am I defining the permutation well

functionpermutation

Hi,
I am trying to create a function which generates a Eulerian number for given n and k. This number should be generated by the recurrence relation
P(i,j)=(j+1).*P(i-1,j)+(i-j).*P(i-1,j-1)
I am getting an answer from Matlab yet I don't know if it is correct because I defined P by P=Perms([ones(i):i j]) since I know the first column should be made up of ones. I'm not sure if I defined P for P(i,j) correctly.
Any help please? Thanks a lot!!
function [P]=euler(~)
n=input(' Enter the number n '); % user enters the number to be generated k=input(' Enter the number k '); % user enters the number to be generated
for i=1:n; % defining the number n inputted by the user as a vector in ters of i so as for the function to work out all the terms up to n for j=2:k; % defining the number n inputted by the user as a vector in ters of i so as for the function to work out all the terms up to n P=perms([ones(i):i j]); %defining P
if i>=0 && j==0; %constraints for first iteration
P(i,j)=1; %answer of first iteration
elseif j>=i && i>=0; %constraints for second iteration
P(i,j)=0; %answer of second iteration
end
end
end
for i=1:n; %once again we define i and j for the recurrence relation. Note that i and j start from 2 since when any one of them is 1, for j=2:k; %then i-1=0 or j-1=0, which result in P(0,1) or P(1,0). But zero is not allowed as a column number, hence i and j begin from 2. P=perms([ones(i):i j]) if j<=i; %constraints for the recurrence relation P(i,j)=(j+1).*P(i-1,j)+(i-j).*P(i-1,j-1) %the recurrence relation end end end end

Best Answer

As it stands, your wish to generate that table using that formula with a matlab array P cannot be realized because its first column corresponds to a j-index value of zero, and matlab does not allow zero indices in its arrays. You can, however, define an array Q as being Q(i,j+1) = P(i,j) and generate Q instead. Your formula would then become
Q(i,j+1) = (j+1)*Q(i-1,j+1)+(i-j)*Q(i-1,j)
With that understanding, do this:
N = 9; % <-- Choose whatever value you wish for the table size N
Q = [ones(N,1),zeros(N,N-1)];
for i = 2:N
for j = 1:i-1
Q(i,j+1) = (j+1)*Q(i-1,j+1)+(i-j)*Q(i-1,j);
end
end
Related Question