recursive permutation algorithm in matlab

8 views (last 30 days)
Harel Harel Shattenstein
Harel Harel Shattenstein on 5 Jul 2018
Edited: Guillaume on 5 Jul 2018
I am trying to write a simple, recursive code for finding permutation. with repetition and no matter the complexity
I found this method 1: remove but did not manage to to write undersantd and write the code in matlab
function y=per(v)
if length(v)==1
y=v;
end
for i=1:length(v)
v(i)=[];
per(v)
v(i)=v(i);
end
Second try
function y=perf(v)
y=per(v,length(v));
end
function y=per(v,n)
if length(v)==1
y=v;
end
for i=1:length(v)
v(i)=[];
per(v,n-1)
v([i, n]) = v([n, i]);
end
  2 Comments
Harel Harel Shattenstein
Harel Harel Shattenstein on 5 Jul 2018
I did not posted as it has error and I am sure there are mistakes

Sign in to comment.

Answers (1)

Guillaume
Guillaume on 5 Jul 2018
Edited: Guillaume on 5 Jul 2018
For a start, the algorithm on the page has two input arguments. Both are essential since they change at each recursion. Note that n is only the length of the vector on the first call of the recursion.
Then you haven't implemented swapping. Instead you delete an element. Possibly, you then try to reinsert that deleted element whose value you didn't save, but clearly v(i) = v(i) is simply a no op. Copy something into itself.
Hint: to swap element i and n:
v([i, n]) = v([n, i]);
edit: following your modifications
I do not understand why you modify the algorithm given. The algorithm has if n == 1, why do you change that to length(v)? Again, apart from the first recursion n and length(v) are not the same.
Same thing for the loop. The only thing that need to change are the bounds from 1 to n instead of 0 to n-1.
The algorithm also never deletes elements. It swaps them before and after the recursion.
Oh, and matlab is pass by value whereas the algorithm assumes pass by reference. You need to get the assign the return value of perm back to v

Community Treasure Hunt

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

Start Hunting!

Translated by