Create all combination of strings

11 ビュー (過去 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 Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by