How to design this for-loop?
1 次查看(过去 30 天)
显示 更早的评论
Hello,
I'm writing a code for comparing the position of dots to one another and i'm having trouble coding for-loops for efficiency. This is the code:
for iS=1:length(RealSPs1)
for iC=1:NClust
D1(iS,iC) = min(abs(RealSPs1(iS)-SPs{iC}));
end
end
for iS=1:length(RealSPs2)
for iC=1:NClust
D2(iS,iC) = min(abs(RealSPs2(iS)-SPs{iC}));
end
end
This code works perfectly fine and D gives a nice 10x3 matrix. Which is what I want. However, I also have the same loop for D3 and, possibly up to D5 or D6. Besides the fact that it takes up a lot of space, the number of D can vary depending on NClust and adding more or less of these blocks of code when NClust has a different value seems very time consuming. So, is there a way to make a for-loop that stacks all iterations of D in some sort of 10x3xNClust array?
3 个评论
Stephen23
2017-11-2
编辑:Stephen23
2017-11-2
"So, is there a way to make a for-loop that stacks all iterations of D in some sort of 10x3xNClust array?"
Yes, better code design is the solution.
Magically accessing variable names is slow, buggy, complex, insecure, and makes debugging difficult. But you actually have no need to do this: simply use one array and some indexing. Indexing is simple, neat, and highly efficient (unlike what you are proposing).
You should simply put your data into one ND numeric array (if the matrix sizes are compatible), or one cell array (if the number of points can vary between matrices). As you already know the size of the final array, why not simply preallocate an ND numeric array of the correct size and index into that?
Read more here:
@Rik Wisselink: I find that "passionate" distracts somewhat from the fact that TMW has clear guidelines advising to avoid string evaluation and all expert users give the same advice, because it makes it seem like one "passionate" old guy is something that can be safely ignored...
Rik
2017-11-2
Fair enough. I'll change the text. I thought it was a good way to give credit where credit is due, but you are right, it might take away some of the message we both want to convey: people shouldn't use it.
回答(0 个)
另请参阅
类别
在 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!