Why is the conditional statement not working as per the condition given?

2 次查看(过去 30 天)
horizon=0.3;
spacing=0.1;
length=1;
numberOfParticlesAlongX=floor(length/spacing);
numberOfParticlesInDomain=numberOfParticlesAlongX; %Number of particles in X-direction attributed to domain
xComponent(1:numberOfParticlesAlongX)=((1:numberOfParticlesAlongX)-1)*spacing; %Co-ordinate of each particle stored in xComponent
CORD=xComponent;
for i=1:numberOfParticlesInDomain
p=1;
for j=1:numberOfParticlesInDomain
if i~=j %Condition for checking undesired presence of a particle in its own neighbourhood
d=abs(CORD(i)-CORD(j)); %Distance between the two particles is stored in'd' for comparison with the horizon value
if d<=horizon
neighbourhoodArray(i,p)=j;
p=p+1; %'p' is incremented at every step to store only the particles within the horizon distance of a particular particle.
end
end
end
end
disp(neighbourhoodArray);
2 3 0 0 0 1 3 4 0 0 1 2 4 5 6 2 3 5 6 0 3 4 6 7 0 3 4 5 7 8 5 6 8 9 10 6 7 9 10 0 7 8 10 0 0 7 8 9 0 0
This code is part of a project on material failure modelling. I need to store all the particles (labelled as 'j' in the for loop) within a certain distance (lablled as 'horizon') from a particular particle (labelled as 'i' in the for loop). With the given data of horizon=0.3, spacing (between particles)=0.1, and length=1, number of particles in the domain will come out to be 10. The x-component of 1st particle is '0' and that of the last one is '0.9', as in the 'xComponent' array.
Now, with the given data, for the first particle (with CORD(1)=0), the neighbourhood particles should be those at CORD(2)=0.1 (Particle-2), CORD(3)=0.2 (Particle-3), CORD(3)=0.3 (Particle-4). But, in the neighbourhoodArray array, for the 1st particle, only Particle-2 and Particle-3 are being shown to be in the neighbourhood of Particle-1, which is incorrect.
I ran the code statement-by-statement using 'Step' and found that the compiler is not executing the statement under "if d<=horizon" when 'd' and 'horizon' have the same value (=0.3). I really don't understand what the problem is with the conditional statement, as I think the logic that I have used is correct.

采纳的回答

Cris LaPierre
Cris LaPierre 2024-4-20
编辑:Cris LaPierre 2024-4-20
The issue is that some of your values in CORD have some small error in them due to floating point arithmatic.
horizon=0.3;
spacing=0.1;
length=1;
numberOfParticlesAlongX=floor(length/spacing);
numberOfParticlesInDomain=numberOfParticlesAlongX; %Number of particles in X-direction attributed to domain
xComponent(1:numberOfParticlesAlongX)=((1:numberOfParticlesAlongX)-1)*spacing; %Co-ordinate of each particle stored in xComponent
CORD=xComponent;
CORD(4) - 0.3
ans = 5.5511e-17

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by