Borrar filtros
Borrar filtros

recursive permutation algorithm in matlab

2 visualizaciones (últimos 30 días)
Harel Harel Shattenstein
Harel Harel Shattenstein el 5 de Jul. de 2018
Editada: Guillaume el 5 de Jul. de 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 comentarios
Guillaume
Guillaume el 5 de Jul. de 2018
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 el 5 de Jul. de 2018
I did not posted as it has error and I am sure there are mistakes

Iniciar sesión para comentar.

Respuestas (1)

Guillaume
Guillaume el 5 de Jul. de 2018
Editada: Guillaume el 5 de Jul. de 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

Categorías

Más información sobre Logical 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