Using randperm in a loop
显示 更早的评论
I have a 3x3 cell called VID1. I want to find all possible combinations and store them in a matrix.
Currently Im using the code below. As I will work with HUGE cells later on I need to optimize it:
So what I want is to loop all the combinations in the best way. The code below can select a combination several times unnecessarily.
for oz=1:999
index=randperm(numel(VID1),2);
if ismember(index,a1)==1
continue
end
a1=[a1; index];
end
As an example:
if index=[1 2]
then that combination should no longer be possible
4 个评论
If you want to do all combinations, you should generate the indices instead of relying on a random function to find every last one.
list=1:100;
tries=0;
while any(list~=0)
tries=tries+1;
list(randi(end))=0;
end
tries
For larger lists this number will grow even further.
You should also use the standard indentation. That will help people read your code more easily. You should also comment your code to explain what it is doing (and more importantly, why). If you look at your code in a year, you won't remember why you were doing things the way you did them. Treat your future self as a stranger.
Joel Schelander
2021-4-14
@Joel Schelander: Please compare:
for oz=1:999
index=randperm(numel(VID1),2);
if ismember(index,a1)==1
continue
end
a1=[a1; index];
end
with
for oz=1:999
index=randperm(numel(VID1),2);
if ismember(index,a1)==1
continue
end
a1=[a1; index];
end
You need just to press Ctrl-a Ctrl-i in your local editor before posting the code here to improve the readability of your code. It is a good strategy to make answering as easy as possible for the readers.
Rik
2021-4-14
My comment showed you why you should not be using a random generator to generate all indices.
A nested loop will work perfectly. I suspect the reason it is too slow for you, is that you want to do many combinations. Many combinations take a lot of time. There isn't really a way out of that. Matlab is not a magic wand.
The only way to reduce the processing time, is if there is an actual vectorized solution. You could implement a convolution with a nested loop, but the conv function uses some trick to do it a lot faster. If there is no such trick for your process, you're stuck.
采纳的回答
更多回答(1 个)
类别
在 帮助中心 和 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!