recursive permutation algorithm in matlab

조회 수: 4 (최근 30일)
Harel Harel Shattenstein
Harel Harel Shattenstein 2018년 7월 5일
편집: Guillaume 2018년 7월 5일
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
Guillaume
Guillaume 2018년 7월 5일
did not manage to to write undersantd and write the code in matlab
Why not? What problem did you encouter?
There is no actual question in your post. What are you asking? If you need help with the code you've written then show us that code.
Note that as mentioned on that page, the remove algorithm is not efficient. You'd be better off implementing the last one on that page, the heap algorithm. It's just as easy to write in matlab.
Harel Harel Shattenstein
Harel Harel Shattenstein 2018년 7월 5일
I did not posted as it has error and I am sure there are mistakes

댓글을 달려면 로그인하십시오.

답변 (1개)

Guillaume
Guillaume 2018년 7월 5일
편집: Guillaume 2018년 7월 5일
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by