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

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Joseph Cheng
Joseph Cheng il 18 Lug 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 Commenti
Ajay Pherwani
Ajay Pherwani il 21 Lug 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
Joseph Cheng il 21 Lug 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by