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
b = 2001×1
0 -0.0074 -0.0081 0.0070 0.0158 0.0173 0.0186 0.0251 0.0053 0.0052

댓글 수: 3

Yes, that is a more streamlined way of programming this. However my focus is really on trying to avoid evaluating that if statement 2,000 times. I think if I nest this for loop inside another for loop, that should do it. For example:
num_states = 1000;
for j = 1:2
if j = 2
v_robot = -0.1;
for i = 2:num_states
...
...
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
b = 1×2001
0.0085 0.0147 -0.0021 0.0118 0.0055 0.0027 0.0093 0.0182 0.0066 0.0051 0.0003 0.0025 0.0095 0.0110 0.0235 -0.0022 0.0033 0.0172 0.0000 0.0002 0.0163 0.0233 -0.0046 -0.0034 0.0189 0.0042 -0.0027 0.0132 0.0155 0.0031
Ah! Good call. I can't eliminate the entire for loop due to the rest of the code that I hadn't supplied here, but vectorizing b will allow me to eliminate the if statement and save on processing time. Good solution. Thank you.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2023년 3월 31일

댓글:

2023년 3월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by