MATLAB: How to define an array within a loop. I am trying to calculate and store some variables provided some conditions are true.Can someone please tell me how to correctly define array x(i,j) for this

arrayfor loopif statementMATLAB

for i=0.1:0.1:1
for j=0.1:0.1:1
if(i+j>0.3)
if(i*j<0.5)
x(i,j)=i.^2+y.^2;
end
end
end
end

Best Answer

MATLAB is not some low-level language like C, so you do not need to solve everything with ugly loops and if statements. Learn to write vectorized code, it is neater and faster:
Ivec = 0.1:0.1:1;
Jvec = 0.1:0.1:1;
[Imat,Jmat] = ndgrid(Ivec,Jvec);
out = Imat.^2 + Jmat.^2;
out(Imat+Jmat <= 0.3) = 0;
out(Imat.*Jmat >= 0.5) = 0;
creates this output:
>> out
out =
0 0.0500 0.1000 0.1700 0.2600 0.3700 0.5000 0.6500 0.8200 1.0100
0.0500 0.0800 0.1300 0.2000 0.2900 0.4000 0.5300 0.6800 0.8500 1.0400
0.1000 0.1300 0.1800 0.2500 0.3400 0.4500 0.5800 0.7300 0.9000 1.0900
0.1700 0.2000 0.2500 0.3200 0.4100 0.5200 0.6500 0.8000 0.9700 1.1600
0.2600 0.2900 0.3400 0.4100 0.5000 0.6100 0.7400 0.8900 1.0600 0
0.3700 0.4000 0.4500 0.5200 0.6100 0.7200 0.8500 1.0000 0 0
0.5000 0.5300 0.5800 0.6500 0.7400 0.8500 0.9800 0 0 0
0.6500 0.6800 0.7300 0.8000 0.8900 1.0000 0 0 0 0
0.8200 0.8500 0.9000 0.9700 1.0600 0 0 0 0 0
1.0100 1.0400 1.0900 1.1600 0 0 0 0 0 0
IMPORTANT: Note that you will also need to understand that equality comparisons with floating point numbers can lead to unexpected results:
Which means you are likely to actually want to make comparisons using a tolerance:
tol = 1e-5;
[Imat,Jmat] = ndgrid(Ivec,Jvec);
out = Imat.^2 + Jmat.^2;
out(Imat+Jmat <= 0.3+tol) = 0;
out(Imat.*Jmat >= 0.5-tol) = 0;