Filling in array with specific numbers

22 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2015-3-24
编辑:Stephen23 2015-3-24
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.

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2015-3-23
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 个评论
Star Strider
Star Strider 2015-3-24
@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.

请先登录,再进行评论。

更多回答(1 个)

David Young
David Young 2015-3-23
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(:)];

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by