Create all combination of strings

조회 수: 10 (최근 30일)
Celso Mauro Nhanga Dos Santos
Celso Mauro Nhanga Dos Santos 2021년 3월 6일
댓글: per isakson 2021년 3월 7일
Hello guys,
I need to create a matrix permutation with value from P1:P8. I tried to use the following code:
Pat = sym('p', [1 8]);
pn = nchoosek([Pat],5);
Str = string(pn)
"p1" "p2" "p3" "p4" "p5"
"p1" "p2" "p3" "p4" "p6"
"p1" "p2" "p3" "p5" "p6"
"p1" "p2" "p4" "p5" "p6"
"p1" "p3" "p4" "p5" "p6"
"p2" "p3" "p4" "p5" "p6"
"p1" "p2" "p3" "p4" "p7" ...
The code worked; nevertheles, it gave me only all possible combinations instead of all permutations. Next I tried this following code:
x = sym('p', [1 8]);
K = 5;
C = cell(K, 1);
[C{:}] = ndgrid(x);
y = cellfun(@(x){x(:)}, C);
y = [y{:}];
But the thing is that this code seems a lot for my computer to handle. So would like your help to see if I can generate all permitation of the string P1:P8.
Thank you in advance

답변 (1개)

per isakson
per isakson 2021년 3월 6일
편집: per isakson 2021년 3월 7일
In response to comment
Does the function, cssm(), do what you ask for?
>> all_permutations = cssm( 3, 2 )
all_permutations =
6×2 string array
"p2" "p1"
"p1" "p2"
"p3" "p1"
"p1" "p3"
"p3" "p2"
"p2" "p3"
>>
where
function all_permutations = cssm( n, k )
str = arrayfun( @(jj) "p"+jj, (1:n) );
% or shorter str="p"+(1:n);
all_combinations = nchoosek( str, k );
%
ix = 1;
fac = factorial( k );
all_permutations = strings( size(all_combinations,1)*fac, k );
for combination = permute( all_combinations, [2,1] )
all_permutations( 1+(ix-1)*fac : ix*fac, : ) = perms( combination );
ix = ix + 1;
end
%
test = unique( all_permutations, 'rows' );
assert( all( size(test) == size(all_permutations) ) );
end
  댓글 수: 2
Celso Mauro Nhanga Dos Santos
Celso Mauro Nhanga Dos Santos 2021년 3월 6일
편집: Celso Mauro Nhanga Dos Santos 2021년 3월 6일
I am getting a response with numerical value only. So since I’m using non-numerical value, it’s showing an error.
Thanks for your response.
per isakson
per isakson 2021년 3월 7일
See my extended answer.

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by