Creating permutations of vectors using basic matlab commands such as loops.

6 ビュー (過去 30 日間)
cody madsen
cody madsen 2019 年 10 月 28 日
コメント済み: Daniel M 2019 年 10 月 28 日
In the problem I have to take a vector x = [x1,x2,x3,x4] ,where 0 <= xi <= m, and m is an inputted integer.
For example if m = 1,
I would need to create vectors
[0,0,0,0]
[1,0,0,0]
[0,1,0,0]
[0,0,1,0]
[0,0,0,1]
[1,1,0,0]
all the way to [1,1,1,1]
  2 件のコメント
Daniel M
Daniel M 2019 年 10 月 28 日
編集済み: Daniel M 2019 年 10 月 28 日
Do you have a specific question? What have you tried so far? Also, here is a cheeky way of getting your result:
M = dec2bin(0:15)-'0'; % where 15 is length(x)^2-1
cody madsen
cody madsen 2019 年 10 月 28 日
編集済み: cody madsen 2019 年 10 月 28 日
lets say that m = 4 so i would need all permutations of x = [x1,x2,x3,x4] where 0 <= xi <= 4. so I would need all permutations of [0,0,0,0],[1,0,0,0],[1,1,0,0],[1,1,1,0],[1,1,1,1],[2,0,0,0],[2,1,0,0] all the way to [4,4,4,4]
And I dont even know where to begin so I havent tried anything yet.
also i think i have to use a for-loop structure because i will have to use each of these permutations later in the second part of the problem.

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

回答 (1 件)

Daniel M
Daniel M 2019 年 10 月 28 日
You can do it in two lines of code by using ndgrid, and putting the four outputs column-wise into a matrix. That would be the most efficient way. If you're required to use loops, that is lame.
[a,b,c,d] = ndgrid(0:4);
M = [d(:) c(:) b(:) a(:)];
  4 件のコメント
cody madsen
cody madsen 2019 年 10 月 28 日
for example I would have T(x) = [x1,x2,x3,x4] and use a loop
something like
count = 0
for k= 1: (total number of vectors)
while T(k) ~= [0,0,0,0]
T(k) = (some manipulations)
count = count + 1
end
end
there is obviously more to it than that but that is as example of how I would be using the vectors later in the program
Daniel M
Daniel M 2019 年 10 月 28 日
Right, but all the vectors would be stored as rows in the matrix T. We're saying the same thing. As for your algorithm, start by calculating how many iterations you'll need, given N number of elements and M number of spots. E.g. you already know for N = 5 (from 0:4) and M = 4 the number of rows of T is 625. But how is that calculated?
Then start very simply using only M = 2 and N = 2, and see if you can code that properly.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by