필터 지우기
필터 지우기

All Possible Matrix Permutations

조회 수: 3 (최근 30일)
Shawn Cooper
Shawn Cooper 2020년 6월 18일
댓글: Akira Agata 2020년 6월 19일
I am trying to write a program that takes integers (or any value, really) and square matrix size m as inputs and returns all possible mxm matrices with those inputs as matrix entries. It would look something like this example input:
allMatrices([0 1],2)
Which would return all 2x2 matrices with 0 and 1 as matrix entries ([0 0; 0 0], [0 0; 0 1], [0 0; 1 1], etc). I would also like to store the matrices so that they can be called individually (M_1, M_2, and so on).
My current strategy is to use
A = unique(nchoosek(repmat('10', 1,4), 4), 'rows')
This lets me index the values A(1:4) as characters for the first 4 entries in a 2x2 matrix, at which point I can use a for-loop to index the remaining entries.
I need to know how to go from my 4 character array ('0000') to a 2x2 matrix ([0 0;0 0]).
And, as always, if there is a more elegant way to do this, please let me know.
Thanks!

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 6월 18일
편집: Ameer Hamza 2020년 6월 18일
Starting with char array '10' to create such matrices does not seems to be a good strategy. It is possible, but better to use numeric datatypes from the beginning.
The following code creates a 3D matrix with all possible permutation along the 3rd dimension.
N = 2;
n2 = N^2;
x = repmat({[0, 1]}, 1, n2);
M = reshape(combvec(x{:}), 2, 2, []);
Result
>> M(:,:,1)
ans =
0 0
0 0
>> M(:,:,2)
ans =
1 0
0 0
>> M(:,:,5)
ans =
0 1
0 0
>> M(:,:,end)
ans =
1 1
1 1
It shows a few permutations of the matrix.
  댓글 수: 3
Ameer Hamza
Ameer Hamza 2020년 6월 18일
I am glad to be of help!
Akira Agata
Akira Agata 2020년 6월 19일
+1
If you don't have Deep Learning Toolbox, one possible workaround will be like this:
[p,q,r,s] = ndgrid([0 1]);
C = mat2cell([p(:),q(:),r(:),s(:)],ones(numel(p),1));
M = cellfun(@(x) reshape(x,[2 2]),C,'UniformOutput',false);
Result is:
>> M{1}
ans =
0 0
0 0
>> M{2}
ans =
1 0
0 0
...
>> M{end}
ans =
1 1
1 1

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by