Dynamic matrix columns combinations

4 次查看(过去 30 天)
mrish
mrish 2024-6-11
评论: Stephen23 2024-6-11
Hello,
I would like to find all possible combinations of a matrix columns, with each column contribute a value, in each itteration of a loop. The matrix size changes in each itteration. For example:
A = [1 2 3
4 5 6
7 8 9].
should produce:
1 2 3
1 2 6
1 5 3 etc.
but should not produce:
1 4 2 for example.
My problems:
  • When insert the matrix to combvec function nothing happens. The function accept vectors - and since I do it with different matrix size in each Itteration of a loop I can't write it manually.
  • ndgrid also requires vectors - and since I need to choose a combination index in other variable - I'm not clear how this happens.
  • I don't have combination function in my Matlab version.
Is there a way to define vectors dynamically in a loop? any idea on to how overcome this? Do I need to write a combination function myself?
  1 个评论
Stephen23
Stephen23 2024-6-11
"Is there a way to define vectors dynamically in a loop?"
What exactly do you mean?

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2024-6-11
编辑:Stephen23 2024-6-11
"any idea on to how overcome this? Do I need to write a combination function myself?"
Use NDGRID with some comma-separated lists:
A = [1,2,3;4,5,6;7,8,9]
A = 3x3
1 2 3 4 5 6 7 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
C = num2cell(A,1);
N = numel(C);
[C{:}] = ndgrid(C{:});
M = reshape(cat(1+N,C{:}),[],N)
M = 27x3
1 2 3 4 2 3 7 2 3 1 5 3 4 5 3 7 5 3 1 8 3 4 8 3 7 8 3 1 2 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  1 个评论
Stephen23
Stephen23 2024-6-11
If you really need just one combination on each loop iteration, then use the methods already described e.g.:
Note that for large arrays you will have a very large number of combinations.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by