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

조회 수: 1 (최근 30일)
Ajay Pherwani
Ajay Pherwani 2014년 7월 18일
댓글: Joseph Cheng 2014년 7월 21일
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
Joseph Cheng 2014년 7월 18일
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
Ajay Pherwani
Ajay Pherwani 2014년 7월 21일
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 2014년 7월 21일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by