MATLAB Answers

How to simplify the loops of a matrix

2 views (last 30 days)
Walker
Walker on 6 Feb 2020
Edited: Rik on 6 Feb 2020
Hello. I have an issue with a code performing some calculations in two loops . It is very slow since I am using two loops. Could you please help me solve this,
Clear all
nx = 100;
ny = 200;
phi = random(nx,ny);
num = 5;
phi1 =zeros(nx,ny);
for i =1:nx
for j = 1:ny
phi1 = mod(phi(i,j), num);
end
end
figure1
surf(phi1)

  0 Comments

Sign in to comment.

Accepted Answer

Robert U
Robert U on 6 Feb 2020
Hi Xinyuan,
the code snippet you are providing does not make any use of the two for-loops. You can remove them, since the function mod() is applied to each element of the matrix "phi". The result is the same. Your code just overwrites the same matrix for nx x ny times.
clear all
nx = 100;
ny = 200;
phi = rand(nx,ny);
num = 5;
phi1 = mod(phi, num);
figure
surf(phi1)
Kind regards,
Robert

  4 Comments

Show 1 older comment
Rik
Rik on 6 Feb 2020
If you insist on a loop you must index the output:
phi1(i,j)=mod(phi(i,j), num);
But the code Robert posted should work as needed.
Two additional points: there is no reason whatsoever to use clear all here. Either omit the all, or replace the line with clearvars. The other point is that you should avoid i and j as variable names. They can cause confusion with the imaginary unit, leading to strange bugs.
Walker
Walker on 6 Feb 2020
@Robert,@Rik, Thank you very much for your reply. I'm learning matlab. It helps me a lot. I understand that , for my case, the two loops are not necessary.
Robert U
Robert U on 6 Feb 2020
Hi Xinyuan,
your introduced change illustrates the problem that you solved partially yourself posting the former code snippet:
Remove the two for-loops and the indexing. The function mod() performs the modulo-operator on each single element of the matrix phi, thus there is no loop necessary.
Kind regards,
Robert

Sign in to comment.

More Answers (0)