Filling in array with specific numbers
42 ビュー (過去 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
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
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
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
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(:)];
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!