How to represent set of sets in MATLAB?

I want to create a series of sets C that
... ...
So i use the code
N = 10;
C{1} = []; % C_0 because MATLAB index starts from 1
C{2} = 1:N;
C{3} = zeros(1,length(C{2})*N);
count = 0;
for r = 1:length(C{2})
ri = C{2}(r);
for s = ri+1:N
count = count + 1;
ri2 = [ri,s]
C{3}(count) = ri2; % Error: Unable to perform assignment because the left and right sides have a different number of elements.
end
end
C{3} = C{3}(C{3}~=0);
How can i fix this code and improve efficiency?
Thanks

 Risposta accettata

Walter Roberson
Walter Roberson il 27 Apr 2020
Modificato: Walter Roberson il 28 Apr 2020
Use a single cell array, with one entry for each of the number of levels you want to carry this out to. Each entry will be a numeric array with the same number of columns as (cell index minus 1)
To get level M from level (M-1), take the array from level M-1 and find out how many rows it currently has, R. Now repmat() the content of that previous level vertically N times, and append a new column which is the elements 1:N repeated vertically R times each.
The only explicit loop needed is according to the number of levels you are using. (repmat or repelem might use implicit loops.)

4 Commenti

Thank you for reply so soon!
Do you mean this:
rowNum = size(C{j},1);
a = repmat(C{j},N,1);
b = repelem((1:N)',rowNum,1);
C{j+1} = [a,b];
But in this way, it will create a lot of unwanted rows like: duplicate rows, like (1,2) and (2,1) are the same; and rows with same elements (1,1), (2,2) ...
Good points about the unwanted entries.
For any given existing row, you can setdiff(1:N, row) to get the list of values that can be appended this time. A faster way to do that might be
N1 = 1:N;
v = true(1,N);
v(row) = false;
avail = N1(v);
Hi Walter, thank you for detailed replying. However, when I got to three-number sets, how can I avoid duplicate rows like (8,18,2) and (18,2,8) and so on?
Furthermore, with more elements in sets (my target is 10-element set), duplicate rows are way too many to accelerate the algorithm.
Thank you very much for your time.
N = 10;
C = cell(N,1);
C{1} = [];
C{2} = (1:N).';
for K = 3 : N
old = C{K-1};
nold = size(old,1);
nnew = N-K+2;
new = cell(nold,1);
for r = 1 : nold
avail = old(r,end)+1:N;
new{r} = [repmat(old(r,:),length(avail),1), avail(:)];
end
C{K} = vertcat(new{:});
end
C{N+1} = 1:N;

Accedi per commentare.

Più risposte (0)

Prodotti

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by