Remove for loop and reduce time
이전 댓글 표시
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
Nithin Banka
2018년 6월 29일
So you want to replace 4th column of 'acc_dis' with the number of times integer 'i' appears in 'grp_ac'?
Nagesh A P
2018년 6월 29일
Nithin Banka
2018년 6월 29일
Then, what I though of is, instead of calling sum() in every loop iteration, since 'i' cannot be beyond the length 17. So we define a temporary array with the length of 'i' and then run a loop through 'grp_ac' and increment the temporary array element according to the number. That way we just need to run through all the elements in grp_ac once to get the required answer. I hope this will take less time.
I know this is not so clear. Can you tell me the size of 'grp_ac'? I will try reproducing what I told you and post you the code if I get good results.
Nagesh A P
2018년 6월 29일
Jan
2018년 6월 29일
@Nagesh A P: Please post a relevant set for the input data.
채택된 답변
추가 답변 (1개)
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
Nagesh A P
2018년 6월 29일
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
2018년 6월 29일
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!