I want to apply a for loop to an array (say [1 2 3]) so that the output gives every possible combination of that array (i.e. [123], [132], [213], [231], [312], [321])

2 ビュー (過去 30 日間)
%this is the code i have present%
%Selection Sort - Iterating Arrays%
%1. Define input array and variables%
a = input('Please enter a list of numbers: ');
n=length(a);
%2. For loop - finding min index in list%
for i=1: n-1
imin=i;
for j=i+1:n
if a(j)~=a(imin)
imin=j;
%3. swapping elements - forming temp variable%
if imin~=i
temp=a(i);
a(i)=a(imin);
a(imin)=temp
end
end
end
end
%4. Displaying results%
disp(a)
%But it only gives 3 of the possible combinations%
%any help would be much appreciated%

採用された回答

Jan
Jan 2018 年 3 月 19 日
編集済み: Jan 2018 年 3 月 19 日
result = perms(1:3)
This replies a matrix, which contains the permutations as rows. If you really want the number 123 instead of the vector [1,2,3], use:
result = perms(1:3) * [100; 10; 1]
  2 件のコメント
Stephen23
Stephen23 2018 年 3 月 19 日
+2 I wish I could give two votes for this. Brilliant.
Jan
Jan 2018 年 3 月 19 日
@Stephen: Thanks. I hope, I n more can offer even more sophisticated methods than a matrix multiplication ;-)

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

その他の回答 (1 件)

Akira Agata
Akira Agata 2018 年 3 月 19 日
If the input is 1-by-3 array with different digits, like [1 2 3], the following code generates all possible combination.
a = [1 2 3];
c = cellstr(num2str(a'))';
% List of all possible combination
[x,y,z] = meshgrid(c,c,c);
list = strcat(x(:), y(:), z(:));
  2 件のコメント
Stephen23
Stephen23 2018 年 3 月 19 日
編集済み: Stephen23 2018 年 3 月 19 日
@Jos (10584): I guess it was a literal interpretation of what is shown in the question title: i.e. [123] rather than [1,2,3] . Using chars makes sense for that case, but judging by the OP's code I doubt that this was their intention.

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

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by