Given vector with N entries, generate all combinations with K entries such that K > N, vector entries can repeat

1 回表示 (過去 30 日間)
I'm writing a script to work some ideas I had with eigenvalues in a triangular matrix, and part of that is generating all the possible permutations of the eigenvalues in an arbitrarily sized matrix. To do this I want to generate vectors I can feed into the diag(v) function where v is composed solely of 1x1 symbolic variables.
For example: I have 2 symbolc variables a and b, that I want to feed into a 4x4 matrix so that I get all combinations of a and b across the main diagonal. This would create a matrix (or a set of vectors) that looks something like:
[a a a a
a a a b
a a b a
a b a a
a a b b
a b a b
a b b a
a b b b
b b b b
b b b a
b b a b
b a b b
b b a a
b a b a
b a a b
b a a a]
which I'll then be able to iterate over to feed into diag.
Thanks!

採用された回答

Matt J
Matt J 2023 年 10 月 20 日
編集済み: Matt J 2023 年 10 月 20 日
syms a b
k=4;
[C{k:-1:1}]=ndgrid([a,b]);
result=reshape(cat(k+1,C{:}) ,[],k)
result = 

その他の回答 (2 件)

Matt J
Matt J 2023 年 10 月 20 日
編集済み: Matt J 2023 年 10 月 20 日
Starting with R2023a,
syms a b
k=4;
v=repmat( {[a,b]},1,k);
result=table2array(combinations(v{:}))
result = 
  4 件のコメント
Bruno Luong
Bruno Luong 2023 年 10 月 20 日
編集済み: Bruno Luong 2023 年 10 月 20 日
I prefer cell array for mixed data types (would not know if I ever use that use case), array on pure numerical data.
At least I want an option to do it. Table is NOT a serious computing data types in my opinion. Nobody really knows the internal structure and complexity of accessing data (what I know is row access is poor). I would not use it in any program excepted for importing data, and final reprentation for user interface.
Alexander
Alexander 2023 年 10 月 20 日
Thanks for the two answers, I had to use your other one because I'm on R2022a (student, don't feel like continuously paying for updates) but Bruno does bring up a good point about the table datatype not being the best for serious computing.

サインインしてコメントする。


Voss
Voss 2023 年 10 月 20 日
syms a b
v = [a b];
n = numel(v);
k = 4;
result = v(dec2base(0:n^k-1,n)-'0'+1)
result = 

カテゴリ

Help Center および File ExchangeNumber Theory についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by