How can I replace the position of moving object indexed of outer for loop, and let that object indexed by the inner for loop in the next iterations ?

6 views (last 30 days)
I deployed an object, this object moves from point to point after testing all direction via inner loop, that object chooses the direction that produce maximum value.
My question in the second iteration how can I let the New position (new_max_1 ) be as original position and in the third iteration again the new position be original position and son on.
EXAMPLE, if the original position of the deployed object is [50 -50 ] after testing three angles we found the angle =45 produced maxvalue so that object will select the position with angle=45 which is represents the new_max_1 position, Now in the second Iteration I want the object start from the new position or consider the new_max_1 as original in this equation newPos_1(i,:) =oldPos_1 + dispacement(i,:), in the second or third iteration and so on I want replace the oldPos_1 in new_max_1. Please have a look at the attached code
thanks in advance for any help
oldPos_1 = [50 -50]; % orignal position of an object
v1 =2m/s % velocity of object
for j = 1:100
% loop of point 1
for bestPos_1 = 1:1
angles = [23 45 90] % angles in degree
for i_1=1:1:numel(angles) % 1:1:3
theta_1 = angles(i) % select angle ascendingly
displacement(i,:) = [cos(theta_1) .* v1 ,sin(theta_1) .* v1]; % Rotated displacement
newPos_1(i,:) =oldPos_1 + dispacement(i,:)
Value_1(i_1) = some calculation depends on the location of that deployed object
end
[maxuValue_1(countmax), idx_max1] = max(Value_1(:));
angle_produceMaxVlue = angles(idx_max1);
displacement(bestPos_1) = [cos(angle_produceMaxVlue) .* v1 ,sin(angle_produceMaxVlue) .* v1];
new_max_1(bestPos_1) = old+ displacement(bestPos_1)
end
end

Answers (1)

ag
ag on 12 Mar 2025 at 17:10
Hi Omar,
To update the position of the object in each iteration such that the new position becomes the starting point for the next iteration, you need to update "oldPos_1" with the value of "new_max_1" at the end of each outer loop iteration.
Here's how you can modify your code:
% rest of the code
for bestPos_1 = 1:1
% rest of the code
oldPos_1 = new_max_1; % update oldPos_1 with new value at the end of the loop
end
Hope this helps!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!