How to simplify the loops of a matrix

조회 수: 1 (최근 30일)
Walker
Walker 2020년 2월 6일
편집: Rik 2020년 2월 6일
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)

채택된 답변

Robert U
Robert U 2020년 2월 6일
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
Walker
Walker 2020년 2월 6일
@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 2020년 2월 6일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by