Get rid of for loop

4 views (last 30 days)
Alexander Nee
Alexander Nee on 24 Mar 2021
Commented: Alexander Nee on 24 Mar 2021
Hello,
I need to get rid of loops in my Matlab code. During this procedure, i encountered the following problem. Here is the part of the code
Nx=11; Ny=11;
A=rand(Ny,Nx);
A1=A;
for j=2:Ny-1
for i=2:Nx-1
A(j,i)=A(j,i-1);
end;
end;
A1(2:Ny-1,2:Nx-1)=A1(2:Ny-1,1:Nx-2);
A2=A-A1;
I get that A is not equal to A1. The situation is the same with the j-1 index on the right side. I found out that in the case of
A1(2:Ny-1,2:Nx-1)=A1(2:Ny-1,1:Nx-2)
Matlab does only 1 operation instead of filling the entire matrix. However, if we take the index i + 1 or j + 1, then everything works fine. Is there any way to fix it without using the loops?
  2 Comments
Alexander Nee
Alexander Nee on 24 Mar 2021
Because I do parallel GPU computing.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 24 Mar 2021
Consider the difference between
for j=2:Ny-1
for i=2:Nx-1
A(j,i) = A(j,i-1);
end
end
and
old_A = A;
for j=2:Ny-1
for i=2:Nx-1
A(j,i) = old_A(j,i-1);
end
end
In the second of those, it is clear that none of the assignments into A can possibly affect the data that is to be copied. But in the first one, for each row, the first column, A(j,1) is copied into A(j,2), and then the next i iteration, A(j,2) is copied into A(j,3) -- but the A(j,2) is the one that was just copied from A(j,1). So the effect of your code is to copy the first entry of each row into all the other columns of the same row, except for the last column (because you stop at Nx-1 )
When you do a vectorized copy such as
A1(2:Ny-1,2:Nx-1)=A1(2:Ny-1,1:Nx-2);
then MATLAB is internally doing the equivalent of copying to a tempory array and doing the assignments out of that copy. Values are not propogated across. The internals are
temporary = A1(2:Ny-1,1:Nx-2);
A1(2:Ny-1,2:Nx-1) = temporary;
-- the act of indexing causes a temporary array with the selected data to be created, and data is copied out of that temporary into the destination locations.
If you wanted to copy the first element of each column across to all columns except the last, then
A(:,2:end-1) = A(:,1).*ones(1,size(A,2)-2);
  3 Comments
Alexander Nee
Alexander Nee on 24 Mar 2021
Thank you so much for the clear explanation!

Sign in to comment.

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!

Translated by