Remove for loop and reduce time

6 ビュー (過去 30 日間)
Nagesh A P
Nagesh A P 2018 年 6 月 29 日
コメント済み: Nagesh A P 2018 年 6 月 29 日
I want to reduce the running time of my code. I found that most of the time in my code is spent in this loop, as this loop is invoked multiple times in my code. Is there anyway to reduce time?? Code explanation: ac1 is an acceleration matrix having values ranging from -10 to 10. I am using discretize function to group different acceleration values into different bins, represented by edges_a. Now, I have to find how many values are there in each bin and store those values in the fourth column of acc_dis matrix.
Here is the code:
if true
edges_a=min(ac1):1.25:max(ac1);
grp_ac=discretize(ac1,edges_a);
for i=1:length(edges_a)
acc_dis(i,4)=sum(grp_ac==i);
end
end
  5 件のコメント
Nagesh A P
Nagesh A P 2018 年 6 月 29 日
grp_ac is an 18000x1 array. It's not fixed, it will change in each iteration. But always between 17500 to 18500. But that won't matter to you. U can use even a 100x1 array as grp_ac for example I guess.
Jan
Jan 2018 年 6 月 29 日
@Nagesh A P: Please post a relevant set for the input data.

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2018 年 6 月 29 日
Points for using discretize instead of writing your own loop for that. The thing is, what you really want is the histogram and there's also a function for that: histcounts:
edges_a = min(ac1):1.25:max(ac1);
h = histcounts(ac1, edges_a);
acc_dis(1:numel(h), 4) = h;
Note: I don't know how many rows acc_dis has. Hopefully at least enough. If it already has the correct number of rows, that last line can be simplified to:
acc_dis(:, 4) = h;
Note 2: If you still need grp_ac, then:
[h, ~, grp_ac] = histcounts(ac1, edges_a);
  1 件のコメント
Nagesh A P
Nagesh A P 2018 年 6 月 29 日
That was what I was looking for. Thanks.

サインインしてコメントする。

その他の回答 (1 件)

Nithin Banka
Nithin Banka 2018 年 6 月 29 日
編集済み: Nithin Banka 2018 年 6 月 29 日
if true
edges_a=min(ac1):1.25:max(ac1);
grp_ac=discretize(ac1,edges_a);
len = length(edges_a);
auxArr = zeros(len, 1));
len1 = length(grp_ac);
for i=1:len1
if(grp_ac(i)<=len&grp_ac(i)>=1)
auxArr(grp_ac(i)) = auxArr(grp_ac(i)) + 1;
end
end
acc_dis(1:len, 4) = auxArr;
end
I think this should help.
  3 件のコメント
Nithin Banka
Nithin Banka 2018 年 6 月 29 日
The code you used runs through grp_ac in every iteration in the 'grp_ac==i' command. That will make it kind of for loop inside a for loop.
Nagesh A P
Nagesh A P 2018 年 6 月 29 日
Ya. i just checked times. Ur code takes only about half as mine. thanks. But can u optimize it more??

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by