# how to optimize for loops and while loops in m scripts ?

11 views (last 30 days)
Ajay Pherwani on 18 Jul 2014
Commented: Joseph Cheng on 21 Jul 2014
Are there any practices you follow that have a tendency to optimize and reduce the loops in your m-script ? are there any available matlab commands which help you reduce your loops or completely eliminate them ?
generally we come across such loops when we work or arrays or cells, is there a efficient way of working with arrays and cells

Joseph Cheng on 18 Jul 2014
It mostly depends on what you are trying to do when working with arrays or cells. There are matlab commands which can reduce the need to loop through every index or row/column but it all depends on what you're trying to accomplish.
##### 2 CommentsShowHide 1 older comment
Joseph Cheng on 21 Jul 2014
Expand or supply some example of code on what you're trying to accomplish. There should be more detail based to go with what would be fastest way.
Are you using 2 for loops to go through all of the indexes? What are you specifically working with Cells or Arrays or both. Cells will have to take a different methodology. the find(* ) function will work well to find which item is located where in the second if you're using arrays. *ismember() can work as well for arrays as well as the any()
such as
>> a = randi(10,1,10)
a =
9 10 2 10 7 1 3 6 10 10
>> b = randi(10,1,10)
b =
2 10 10 5 9 2 5 10 8 10
>> ismember(a,b)
ans =
1 1 1 1 0 0 0 0 1 1
where there is a 1 for each item in a that shows in in b.
if you're working cells, i would suggest using cellfun() that will perform a user defined function on each cell. So you have one loop that goes through the cell array 1 for the 2nd cell array.
c = {2,4,5,6,8,2,34,6,11,11};
for ind = 1:length(c)
index = find([c{:}] == X; %where X = number you're looking for.
end
or
index = cellfun(@(x,X) x==X, c, 'UniformOutput', 1);
or
index = false(1, numel(c))
for ind = 1:numel(c)
index(ind) = (c{ind} == X);
end

### 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!

Translated by