MATLAB: How make matrix from a for loop

for loop

My code like this,
……….. …………
x_error=zeros(1,1);
y_error=zeros(1,1);
z_error=zeros(1,1);
lz=1.5; %lx=1.35; %ly=1.4;
for i=1:1:5 ly=i;
for j=1:1:5;
lx=j;
......................
X=abs(x(1,1));
Y=abs(x(1,2));
H=abs(x(1,3));
x_error(i,j)=abs(X-lx);
y_error(i,j)=abs(Y-ly);
z_error(i,j)=abs(abs(z1-H)-lz);
end
end
x_er=x_error
y_er=y_error
z_er=z_error
it's work but when i change i=1:1:5 to i=1:0.1:5 and j=1:1:5; to j=1:0.1:5;
then error like this >>Attempted to access x_error(1.1,1); index must be a positive integer or logical.
how can i solve this i need to get the x_error value in matrix form not in a cell array form

Best Answer

Since the two for loops now iterate with a step size of 0.1, then i and j are no longer positive integer values (1,2,3,4,5, etc.) and so accessing the arrays will fail with the ..index must be a positive integer or logical error message for rational values like 1.1,1.2,1.3,etc.
To accommodate this, you could do the following: realize that the number of elements in 1:0.1:5 is just 41 (try length(1:0.1:5)), pre-allocate memory to your matrices, and use local variables to act as your step sizes:
n = length(1:0.1:5);
% pre-allocate memory to the error arrays
x_error = zeros(n,n);
y_error = zeros(n,n);
z_error = zeros(n,n);
% initialize the step sizes
lx = 1;
ly = 1;
% loop
for i=1:n
% re-initialize lx to be one ---> new code!
lx = 1;
for j=1:n
% do stuff
% set the errors
x_error(i,j)=abs(X-lx);
y_error(i,j)=abs(Y-ly);
z_error(i,j)=abs(abs(z1-H)-lz);
% increment lx ---> new code!
lx = lx + 0.1;
end
% increment ly ---> new code!
ly = ly + 0.1;
end
This way, the code will always be using positive integers to access the error arrays. Try the above and see if it helps!