Making loop calculate-able
조회 수: 1 (최근 30일)
이전 댓글 표시
n = 450*450;
for i = 0:1:n
for j = 0:1:n
i = mod (i+1,n+1);
j = mod (j + S(i+1), n+1);
S([i+1 j+1]) = S([j+1 i+1]);
end
end
I need to run this code for initial sequence S = {1,2,3,...,450*450}, but due to very high computation matlab is not able to do this. Is there any way to acheive this using less calculations?
댓글 수: 2
Walter Roberson
2019년 6월 18일
Are you sure the loop is correct? You have for i then for j and inside that you modify i . The i value is going to be reset every time that a new for i iteration starts.
답변 (2개)
Guillaume
2019년 6월 18일
편집: Guillaume
2019년 6월 18일
Even if your code is correct, it is extremely bad practice to use the same variable names for the loop indices and for local variables within the loop. Certainly any experience coder will pause when looking at that code and start to wonder if there's a bug, as Wallter did. Make the life of the reader easier, remove the ambiguity:
n = 450*450;
for i = 0:1:n
for j = 0:1:n
ind1 = mod(i+1, n+1) + 1;
ind2 = mod(j + S(ind1), n+1) + 1;
S([ind1, ind2]) = S([ind2, ind1]); %swap linear indices ind1 and ind2
end
end
In the calculation of ind2 (your original 2nd j), it is unclear if you meant to use the loop index i or the i calculated on the previous line. Your code would have used the i calculated on the previous line, so i have done the same.
Note that your S needs to have n+1 elements for your code to work. Are you sure you didn't mean mod(..., n)?
edit: As for speeding it up, no it's not possible because of the dependence on S(ind1) in the calculation of ind2. And since you want to do swaps = 41,006,655,001 swaps ~= 41 billions swap, it's going to take a loooong time, but matlab will eventually get you the result. It takes about 0.3 seconds on my machine to do one i loop, so in about 18 hours you'd get your result. Do you actually need to do that many swaps?
댓글 수: 6
Guillaume
2019년 6월 18일
편집: Guillaume
2019년 6월 18일
Since Walter removed your explanation, I have no idea what the intent of your code is. You can explain it without mentioning encryption.
As I said, as I, there's no way to speed up this code because of the depency on S in the calculation of ind2. if you remove that dependency, then the index calculation can be sped up, but you'll still have to perform 41 billion swaps which is always going to take a while. The only way to significantly speed up the code is by greatly reducing the number of swaps needed. performing 202,501 swaps takes only 0.3 seconds on my machine. But doing these 202,501 swaps another 202,501 times is 202,501 * 0.3 seconds ~= 18 hours!
참고 항목
카테고리
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!