MATLAB Answers

Vectorize two for loops

2 views (last 30 days)
Master Blabla
Master Blabla on 19 Nov 2020
Answered: CHENG QIAN LAI on 24 Nov 2020
How to vectorize this function:
for i=1:100
for j=1:200
TheOne(i,j) = i+j;
end
end

  0 Comments

Sign in to comment.

Answers (2)

David Hill
David Hill on 19 Nov 2020
Edited: David Hill on 19 Nov 2020
[i,j]=meshgrid(1:100,1:200);
TheOne=reshape(sum((Png1(:,i)-Png2(:,j)).^2),100,[]);

  4 Comments

Show 1 older comment
David Hill
David Hill on 19 Nov 2020
Does not get any simpler.
Master Blabla
Master Blabla on 19 Nov 2020
It does not work correctly
David Hill
David Hill on 19 Nov 2020
Made a mistake. Try this.
[i,j]=meshgrid(1:100,1:200);
TheOne=reshape(sum((Png1(:,i)-Png2(:,j)).^2),200,[])';

Sign in to comment.


CHENG QIAN LAI
CHENG QIAN LAI on 24 Nov 2020
[i,j]=ndgrid(1:100,1:200);
% 1 2 3 . . . 200
%---------------------------
% i= 1 1 1 . . . 1 | 1
% 2 2 2 . . . 2 | 2
% 3 3 3 . . . 3 | 3
% . . . | .
% . . . | .
% . . . | .
% 100 100 100 . . . 100 | 100
%---------------------------
% j= 1 2 3 . . . 200 | 1
% 1 2 3 . . . 200 | 2
% 1 2 3 . . . 200 | 3
% . . . | .
% . . . | .
% . . . | .
% 1 2 3 . . . 200 | 100
TheOne = i+j;

  0 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!