Changing the values of an array with an if condition inside a for-loop

3 views (last 30 days)
Hi everyone,
So I have this code:
% Repulsive forces (Fr)
rho_r = sqrt((x-xo).^2+(y-yo).^2);
if rho_r > rho_0
Fr(1,1) = 0;
Fr(2,1) = 0;
elseif rho_r <= rho_0
Fr(1,1) = Fr(1,1)-Kr*(x-xo)*((rho_r-rho_0)/rho_r);
Fr(2,1) = Fr(2,1)-Kr*(y-yo)*((rho_r-rho_0)/rho_r);
end
Frc = [Frc Fr];
And the first values for x and y are as follow. The values inside the array xo and yo are:
x = 15
y = 10
xo = [20 30 35 50 65]
yo = [13 25 35 38 45]
As you can see with those values for x and y, the elseif should be operating however I still have Fr == 0. I've tried some things out but it still doesn't work. I even created a for loop just as followed:
rho_r = sqrt((x-xo).^2+(y-yo).^2);
for i = 1:5
if rho_r(1,i) > rho_0(1,i)
Fr(1,i) = 0;
Fr(2,i) = 0;
elseif rho_r(1,i) <= rho_0(1,i)
Fr(1,i) = Fr(1,i)-Kr*(x-xo(1,i))*((rho_r(1,i)-rho_0(1,i))/rho_r(1,i));
Fr(2,i) = Fr(2,i)-Kr*(y-yo(1,i))*((rho_r(1,i)-rho_0(1,i))/rho_r(1,i));
end
end
Sorry my bad i forgot to add the values of rho_0 and Kr:
rho_0 = [7 4 5 3 4];
Kr = [500 350 500 250 250];
I've attached the full code

Answers (1)

Birdman
Birdman on 2 Apr 2020
Edited: Birdman on 2 Apr 2020
Maybe the following code will get you going:
x = 10;
y = 10;
xo = [20 30 35 50 65];
yo = [13 25 35 38 45];
rho_r = sqrt((x-xo).^2+(y-yo).^2);
%dummy data
rho_0=30;
Kr=5;
%initial Fr
Fr=zeros(1,numel(xo));
%change values based on conditions
Fr(rho_r > rho_0)=0;
temp=-Kr*(x-xo)*((rho_r-rho_0)/rho_r);
Fr(rho_r <= rho_0)=temp(rho_r <= rho_0)
EDIT:
rho_r>rho_0
ans =
1x5 logical array
1 1 1 1 1
which means that every value in rho_r is greater than every corresponding value in rho_0. Therefore the following line
Fr(rho_r > rho_0)=0;
works and Fr becomes
Fr =
0 0 0 0 0
  2 Comments
Eneko Cubillas Laiseca
Eneko Cubillas Laiseca on 2 Apr 2020
Thanks a lot, the program is working better but I still have to make some adjustements in order for it to work to its absolut best.
Eneko Cubillas Laiseca
Eneko Cubillas Laiseca on 2 Apr 2020
I've added a condition to your code and it works better. Still have to do some more but thanks you very much :)!
rho_r = sqrt((x-xo).^2+(y-yo).^2);
for i = 1:2
Fr=zeros(i,numel(xo));
end
Fr(rho_r > rho_0)=0;
temp=-Kr.*(x-xo).*((rho_r-rho_0)/rho_r);
Fr(rho_r <= rho_0) = temp(rho_r <= rho_0);
Frc = [Frc Fr];

Sign in to comment.

Categories

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

Community Treasure Hunt

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

Start Hunting!