how make matrix from a for loop

1 view (last 30 days)
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

Accepted Answer

Geoff Hayes
Geoff Hayes on 9 Jun 2014
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!

More Answers (1)

Sara
Sara on 9 Jun 2014
First, when you allocate variables before the for loop, you need to allocate them so that they can contain all the elements. This means that for the code you have posted, x_error = zeros(5,5) and so on. Second, doing loop where the increment is not an integer is not recommendable for numerical reasons. So, create an array before the for loop with the elements you need to evaluate:
myarray_x = 1:0.1:5;
Then use:
for i = 1:numel(myarray_x)
and inside this loop do:
lx = myarray_x(i);

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!