MATLAB Conditions, Loops, and Command Routines · Study
English translation
Topics covered
Execute the same movement plan repeatedly, and write rules to stop on invalid inputs or battery conditions.
Check conditions before commands
if selects code according to the state. Check conditions that determine command validity, such as units, ranges, and battery level, before performing an action.
Loops and state updates
for processes a fixed list in order, while while repeats as long as a condition holds. Update position, progress, and termination conditions at each step to avoid a routine that never stops.
Separate device connections from calculations
First validate with a simulation that accumulates coordinates and records the command list. After checking the plan, connect it to device-specific transmission functions to reuse the rules with other aircraft or libraries.
Worked example
Accumulate coordinates for the four movements of a square with side length .5 m. Do not call communication or flight functions.
moves_m=[.5,0;0,.5;-.5,0;0,-.5];
position_m=[0,0];path_m=zeros(size(moves_m,1)+1,2);
for k=1:size(moves_m,1)
position_m=position_m+moves_m(k,:);
path_m(k+1,:)=position_m;
end
assert(norm(position_m)<1e-12);
plot(path_m(:,1),path_m(:,2),'o-');axis equal;grid on;
xlabel('x [m]');ylabel('y [m]');
Example results
The square ends at (0,0), with a total travel distance of 2 m.