how to optimize for loops and while loops in m scripts ?
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
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 件のコメント
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 Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!