# How to optimize code/avoid a loops

조회 수: 1(최근 30일)
Nik Rocky 25 Jun 2020
댓글: darova 29 Jun 2020
Hello,
I have terrible knowledge of cell arrays and I realized some loops to read and comparing the cell arrays.
If I use big arrays — calculating for every loop takes up to minute for every dataset. It's very inefficient. So, I try to describe my code part:
I have multiple cell-arrays, and I'm read while any time point t_ref_cnt the frequency values in cell M_interpl and Traj_interpl.
If the right time position is chosen, I'm writing values to from M_interpl to motor_actual and Traj_interpl to motorspeed_detected arrays.
After this operation, I have while every t_ref_cnt two Arrays that I can compare (by TP-FN-FP).
Structure of M_interpl is:
1×5 cell array with 1 x 3001 doubles
1. cell is a time t_ref_cnt 0 0,01 0,02 0,03 ... 30,0
2.,3.,4.,5. cells are frequency from 0 to x
Structure of Traj_interpl (depending on of dataset):
example 1×184 cell array with y x 2 doubles (1<y<1000)
1. cell is a time t_ref_cnt 0,03 0,04 0,05 (just small time blocks - not from 0 to 30)
2. cell are frequencys from 1 to 500
I have atatsched both files for example
for t_ref_cnt = 1:length(t_ref) %for every 10ms time step
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for m_interpl_cnt = 2:length(M_interpl) %for any motor-array
for m_row_cnt = 1:length(M_interpl{m_interpl_cnt}) %for any row of single motor
if t_ref(t_ref_cnt) == M_interpl{1}(m_row_cnt) %if right row of motor is choosen
motor_actual(m_interpl_cnt-1) = M_interpl{m_interpl_cnt}(m_row_cnt); %write actual value of motorspeed to array
break;
else
motor_actual(m_interpl_cnt-1) = 0;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for traj_cnt = 1:length(Traj_interpl) %for every Traj-Cell
for t_row_cnt = 1:length(Traj_interpl{traj_cnt}) %for any row of Traj
if t_ref(t_ref_cnt) == Traj_interpl{traj_cnt}(t_row_cnt,1) %if right row of Traj is choosen
motorspeed_detected(traj_cnt) = Traj_interpl{traj_cnt}(t_row_cnt,2); %write detected value to array
break;
else
motorspeed_detected(traj_cnt) = 0;
end
end
end
end
I think there are a better way to solve it!?
Thank you very much in advice!
For better understanding: Best
Nik
##### 댓글 수: 3표시숨기기 이전 댓글 수: 2
darova 29 Jun 2020
• The question is not about interpolation
Well, maybe you should take a look into it. You have some data (time and value) and want to have some values having time1. interp1 can easily handle this task

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

### Community Treasure Hunt

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

Start Hunting!