Creating permutations of vectors using basic matlab commands such as loops.
이전 댓글 표시
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
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
2019년 10월 28일
편집: cody madsen
2019년 10월 28일
답변 (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
cody madsen
2019년 10월 28일
Daniel M
2019년 10월 28일
I highly doubt you're required to store each vector separately. That would be 625 variables. And how are you supposed to utilize 625 variables in a subsequent loop, with 625 different names? As opposed to using one variable, M above, and looping over the rows of it.
cody madsen
2019년 10월 28일
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.
카테고리
도움말 센터 및 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!