0

I need to find all possible combinations of taking r from n numbers in array without duplicates, with repetition, for example from arr = [ 1 2 3] If my r = 2 My result should be:

1 1
1 2 
1 3
2 2
2 3
3 3

I have wrote two functions, one of them is recursive, I get the error: "Out of memory. The likely cause is an infinite recursion within the program."

My code:

function repeat(chosen, arr, index, r, start, ends)
    if(index == r)
        for i = 1:r
           arr(chosen(i))
        end
    end
    for i = start:ends
        chosen(index) = i;
        repeat(chosen, arr, index, r, i, ends)
    end
end

function combs(arr, n, r)
chosen = zeros(1, r+1, 'int8');
repeat(chosen, arr, 1, r, 1, n);
end
  • 1
    Perhaps this file exchange function may help you: [permn](https://www.mathworks.com/matlabcentral/fileexchange/7147-permn). – Thales Nov 09 '19 at 16:44
  • @Thales it helps, but I need to do it manually, without using default matlab functions. – Sophie Garcia Nov 09 '19 at 16:47
  • 1
    This is either a duplicate of your question form yesterday, which explains how to get those combinations, or your question from earlier today that asks about the error in the recursive code. I suggest you edit your question to clearly indicate how it is different from either of those. And please edit your previous question too, it is only now that I understand what that code is meant to do. – Cris Luengo Nov 09 '19 at 17:25
  • @CrisLuengo Now I need to solve my problem without default MATLAB functions, that's why I created a new topic in which I need explanation about my code, not about the matlab functions. – Sophie Garcia Nov 09 '19 at 18:10

0 Answers0