Filling in array with specific numbers

88 views (last 30 days)
Hi, So I have 3 arrays that I would like to combine in a specific order like so:
A = [1;2;3];
B = [a;b;c;d];
C = [I,II,III];
ie:
A = 1 B = a C = I
2 b II
3 c III
d
and want them to be sorted like so:
M = [1,a,I;1,b,I;1,c,I;1,d,I;2,a,I;2,b,I;2,c,I;2,d,I;3,a,I;....etc until... 1,a,II;1,b,II;..etc];
ie: Want to fill the matrix with every combination of the 3 matrices in order like so:
M = 1 a I
1 b I
1 c I
1 d I
2 a I
2 b I
2 c I
2 d I
3 a I
3 b I
3 c I
3 d I
1 a II
1 b II
1 c II
1 d II
2 a II
.. and so on.
Maple has a Fill function which I could use to do this easily, however I couldn't find a similar function in Matlab so I was wondering what the most efficient way of doing it would be.
Thanks in advance.
  1 Comment
Stephen23
Stephen23 on 24 Mar 2015
Edited: Stephen23 on 24 Mar 2015
You might like to have a look at my FEX submission natsrtorows:
This function sorts a cell array of strings into order, taking into account the values of any numeric in the strings. And just like MATLAB's sortrows you can tell it which columns you want to sort by.
So given an input matrix M containing all of the required rows, but in the wrong order, we can simply call natsortrows to sort them into the required order:
N = cellfun(@num2str,M,'UniformOutput',false);
[~,idx] = natsortrows(N,[3,1,2]);
M = M(idx,:);
which sorts by the third, then the first and second columns.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 23 Mar 2015
The only way I can see to do this is with nested for loops:
A = {1;2;3};
B = {'a';'b';'c';'d'};
C = {'I','II','III'};
k = 0;
for k1 = 1:length(C)
for k2 = 1:length(A)
for k3 = 1:length(B)
k = k + 1;
M{k} = {A(k2) B(k3) C(k1)};
end
end
end
Q = M(1:10)' % Sample Output
celldisp(Q) % Display Sample Output
  4 Comments
Star Strider
Star Strider on 24 Mar 2015
@David — Well earned! I went back and ran your code with my cell arrays and it worked as it should. So many functions don’t work and play well with cell arrays, I didn’t try repmat. It turns out repmat doesn’t care what the data type is, so long as the dimensions are compatible.

Sign in to comment.

More Answers (1)

David Young
David Young on 23 Mar 2015
One way, using repmat to make the repeated values:
% test data
A = [1;2;3];
B = [11;12;13;14];
C = [21;22;23];
% compute combination matrix
nA = length(A);
nB = length(B);
nC = length(C);
Acol = repmat(A.', nB, nC);
Bcol = repmat(B, nA*nC, 1);
Ccol = repmat(C.', nA*nB, 1);
M = [Acol(:) Bcol(:) Ccol(:)];

Categories

Find more on Structures in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!