Creating permutations of vectors using basic matlab commands such as loops.
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
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 个评论
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!