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

3 visualizaciones (últimos 30 días)
Ajay Pherwani el 18 de Jul. de 2014
Comentada: Joseph Cheng el 21 de Jul. de 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
0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Joseph Cheng el 18 de Jul. de 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 comentariosMostrar NingunoOcultar Ninguno
Ajay Pherwani el 21 de Jul. de 2014
can you please let me know some of those matlab commands ?
assuming I am trying tofind whether the data in cell/array-1 is present in cell/array 2 ? --> currently for this I have to use "for" or "while" loop for this .
Joseph Cheng el 21 de Jul. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by