Clear Filters
Clear Filters

How to design this for-loop?

2 views (last 30 days)
Wouter Mattheussens
Wouter Mattheussens on 2 Nov 2017
Commented: Rik on 2 Nov 2017
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 Comments
Stephen23
Stephen23 on 2 Nov 2017
Edited: Stephen23 on 2 Nov 2017
"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
Rik on 2 Nov 2017
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.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!