MATLAB: How to set up this for loop correctly

eafor loopnorthwestern

It has been a year since my first MATLAB course and I'm getting back in the swing of things. Writing a script that subs in x values and z values into a matrix equation. Code looks like:
clear;clc;
x=-5:1:5;
z=-5:1:5;
f=zeros(length(x),length(z));
A=zeros(3);
for i=1:length(x)
for j=1:length(z)
xvar=x(i)
zvar=z(i)
A= [ 3/sqrt(34) 2/sqrt(24) -x(i)/sqrt(x(i)^2+z(j)^2+16)
-4/sqrt(34) -4/sqrt(24) -4/sqrt(x(i)^2+z(j)^2+16)
-3/sqrt(34) 2/sqrt(24) -z(j)/sqrt(x(i)^2+z(j)^2+16) ]
B=[0;981;0]
C=A\B
end
end
I would like the script to test the conditions where x=-5, z=-5, then x=-4, z=-5, etc etc all the way through x=z=5, but it instead will test ten identical cases of x=z=-5 before moving onto x=z=-4. I suspect it is an issue with the for loop, but I'm not sure what's going on.
Thanks.
#gocats ?

Best Answer

I’m not certain I understand everything here, but if you want to increment ‘x’ first and increment ‘y’ second, change the ‘xvar’ assignment to:
xvar=x(j)
Right now, they’re both incrementing together with each ‘i’.
By the way, please don’t use ‘i’ and ‘j’ as loop counters or other variables. MATLAB uses them as its imaginary operators, and this could get confusing if you need to use complex variables.