How can I change a variable once at a specific point inside of a for loop?
이전 댓글 표시
I am looking to decrease the run time of a program and was wondering if there is a more efficient way to accomplish the following:
When my for loop reaches a certain point (num_states = 1001), I need the variable v_robot to change from 0.1 to -0.1 (to simulate a change in direction). The snippet of code below using an if statement works, but seems to be computationally heavy, and it is really unnecessary to continue evaluating the if statement once the change has been made. Is there a more efficient way to do what I need without breaking this into 2 for loops (with the variable changing between)?
num_states = 2001;
v_robot = 0.1;
stdev_odometry = 0.1;
delta_t = 0.1;
b = zeros(num_states,1);
for i = 2 : num_states
sensor_noise = stdev_odometry * randn();
% Reverse direction at end of hall
if i <= 1001
b(i) = (v_robot + sensor_noise) * delta_t;
else
b(i) = (v_robot * -1 + sensor_noise) * delta_t;
end
end
답변 (1개)
You can change the sign of v_robot variable
num_states = 2001;
v_robot = 0.1;
stdev_odometry = 0.1;
delta_t = 0.1;
b = zeros(num_states,1);
for i = 2 : num_states
sensor_noise = stdev_odometry * randn();
% Reverse direction at end of hall
if i <= 1001
b(i) = (v_robot + sensor_noise) * delta_t;
else
b(i) = (-v_robot + sensor_noise) * delta_t;
end
end
b
댓글 수: 3
Jesse Kakstys
2023년 3월 31일
If you want to avoid the if-else & for loop to make code run better, vectorize the code statements as below.
num_states = 2001;
v_robot = 0.1;
stdev_odometry = 0.1;
delta_t = 0.1;
b = zeros(num_states,1);
sensor_noise = stdev_odometry * randn(1,2001);
%vectorize the equations
b1 = (v_robot + sensor_noise(1:1001)) * delta_t; % first 1001
b2 = (-v_robot + sensor_noise(1002:2001)) * delta_t; % next 1000
b = [b1 b2] % final vector
Jesse Kakstys
2023년 3월 31일
카테고리
도움말 센터 및 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!