필터 지우기
필터 지우기

Filling in array with specific numbers

조회 수: 22 (최근 30일)
John Andrews
John Andrews 2015년 3월 23일
댓글: Star Strider 2015년 3월 24일
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
David Young
David Young 2015년 3월 24일
Thanks!
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