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.
For loop not working for me
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Alhussein Osama
le 15 Déc 2021
Commenté : Alhussein Osama
le 15 Déc 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.
0 commentaires
Réponse acceptée
Alhussein Osama
le 15 Déc 2021
2 commentaires
Jan
le 15 Déc 2021
I do not agree that this is a working answer. It might work by accident, if the floating point values appear in the vectors, but this is fragile.
Plus de réponses (1)
Jan
le 15 Déc 2021
Modifié(e) : Jan
le 15 Déc 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!
See https://www.mathworks.com/matlabcentral/answers/57444-faq-why-is-0-3-0-2-0-1-not-equal-to-zero .
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);
Eps(mask1) = eplsn_r1;
mask2 = (abs(xx.') == 1.5e-6 | abs(yy) == 0.75e-6);
Eps(mask2) = eplsn_r2;
iteration = nnz(mask1) + nnz(mask2);
For a stable code you have to consider limits. maybe:
(abs(xx.') - 1.75e-6) < 1e-8
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!