- copy-and-pasting code is a sign that code is badly designed. Computers are really good at doing one thing: quickly repeating simple operations in a loop. When you copy-and-paste code like this you are just doing the computer's job for it.
- Dynamic variable names are one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know more: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
Info
This question is closed. Reopen it to edit or answer.
How Create elseif as required inside a loop?
1 view (last 30 days)
Show older comments
Hi, I want to create many nested loop mainly elseif by using a for loop like
for i=1:n
if m(i)>=start && m(i)<=D
a=a+1;
elseif m(i)>=D+1 && m(i)<=D*2
b=b+1;
elseif m(i)>=D*2+1 && m(i)<=D*3
c=c+1;
elseif m(i)>=D*3+1 && m(i)<=D*4
d=d+1;
elseif m(i)>=D*4+1 && m(i)<=D*5
e=e+1;
end
end
Here i want to add more elseif depends on condition automatically inside a the for loop, is it possible to create more 'elseif' or less inside for loop ??
1 Comment
Stephen23
on 29 Mar 2018
Edited: Stephen23
on 29 Mar 2018
"...is it possible to create more 'elseif' or less inside for loop ??"
It is possible, but the two obvious ways of doing this are both bad ways to write code:
MATLAB is a high-level language, and rather than trying to solve everything with loops and if's it is much simpler to use the inbuilt commands. In your case you are counting values, i.e. calculating a histogram, and MATLAB has several histogram functions available:
These will be much simpler and much more efficient to use than dynamically accessing variable names in a loop.
Answers (1)
Walter Roberson
on 29 Mar 2018
edges = [start, D*(1:5)];
counts = histcounts(m, edges);
counts will now be a vector, with counts(1) corresponding to your a, counts(2) corresponding to your b, and so on.
Note that this code will count start <= x < D, then D <= x < D*2, then D*2 <= x < D*3, then D*3 <= x < D*4, then D*4 <= x <= D*5 . Notice that in each case, values exactly equal to the upper bound are not counted in the lower interval, with the exception that the final interval includes values exactly equal to the upper bound. This disagrees with your existing code, which uses start <= x <= D, D+1 <= x <= D*2, D*2+1 <= x <= D*3, D*3+1 <= x <= D*4, D*4+1 < x <= D*5 -- notice the boundary cases.
0 Comments
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!