# For loop not working for me

2 views (last 30 days)
Alhussein Osama on 15 Dec 2021
Commented: Alhussein Osama on 15 Dec 2021
I'm doing some basic for loop that should return epislons for specific values and it's not working at all.
The strange thing is that when I changed the values of xx(i) and increased them it worked fine, when I checked if my conditions are found since that was the obvious mistake, I found them in the matrix of xx but the for loop doesn't assign the values as it should. Not sure what's the mistake here. Thanks a lot
clear
close all
clc
window_x=50e-6; %The window size in x direction (microns)
window_y=50e-6;
dx=2.5e-7; %The step size in x direction
dy=2.5e-7;
x_initial=-window_x/2; %The initial of the x window
y_initial=-window_y/2; %The initial of the y window
xx=x_initial:dx:-1*x_initial;
yy=y_initial:dy:-1*x_initial;
eplsn_r1 = 2.25;
eplsn_r2 = 2.1025;
lmda = 1.5e-6;
k0=2*(22/7)/lmda;
x_initial
xx
[x y]=meshgrid(xx,yy);
N=length(xx);
M=length(yy);
Eps=zeros(N,M);
iteration=0;
for i=1:N
for j=1:M
if (xx(i) ==-1.75e-6 || yy(j)==-1e-6 || xx(i)==1.75e-6 || yy(j)==1e-6)
Eps(i,j)=eplsn_r1;
iteration = iteration+1;
elseif (xx(i)==-1.5e-6 || yy(j)==-0.75e-6 || xx(i)==1.5e-6 || yy(j)==0.75e-6)
Eps(i,j)=eplsn_r2;
iteration = iteration+1;
end
end
end
iteration
I made the iteration to check if it's working and it's returning 0 on my end.

Alhussein Osama on 15 Dec 2021
It worked now, I changed the window size to be smaller and it worked fine. It seems that there's a ratio between the size and the step size that it won't work after it.
##### 2 CommentsShowHide 1 older comment
Alhussein Osama on 15 Dec 2021
I agree with you, but I tried to use your simpler code but it didn't work though. I will try to modify it later to adjust to whay I need to do. Thanks for your help.

Jan on 15 Dec 2021
Edited: Jan on 15 Dec 2021
xx = x_initial:dx:-1*x_initial;
if xx(i) == -1.75e-6
You cannot expect a specific value in the vector xx, because it is created by a mathematical operation with floating point values. See:
xx = 0:0.1:1
any(xx == 0.3) % FALSE!
By the way, a simpler code:
N = length(xx);
M = length(yy);
Eps = zeros(N, M);
mask1 = (abs(xx.') == 1.75e-6 | abs(yy) == 1e-6);
mask2 = (abs(xx.') == 1.5e-6 | abs(yy) == 0.75e-6);
For a stable code you have to consider limits. maybe:
(abs(xx.') - 1.75e-6) < 1e-8
Alhussein Osama on 15 Dec 2021
Oh, I totally forgot that since I have been away from programming for a while, thanks for your reply and your answer though.