how to vectorize these "for loop" ?

3 views (last 30 days)
Anita pawar
Anita pawar on 4 Aug 2017
Edited: KL on 4 Aug 2017
clc;
clear all;
close all;
i=1;
for k=1:1:10;
for a=1:1:10;
for b= 1:1:10;
for c=1:1:10;
nump(i,:)=[k a*k];
denmp(i,:)=[1 b+c b*c];
i=i+1;
end
end
end
end
  1 Comment
Christos Saragiotis
Christos Saragiotis on 4 Aug 2017
If the only reason you want to vectorize is speed and k, b have the same range (i.e. from 1 to 10) and likewise a, c have the same range you can take advantage of this and make this quadruple for-loop a double one.
The following implementation is about 40 times faster than the posted one on my machine:
N = 10; % nb, nk
M = 10; % na, nc
NM = N*M;
Num = zeros(NM,2);
Den = zeros(NM,3);
k = 1;
for n = 1:N;
for m = 1:M;
Num(k,:) = [n n*m];
Den(k,:) = [1 n+m n*m];
k = k+1;
end
end
Denmp = repmat(Den,NM,1);
Num = reshape(Num, 1,NM,2);
Nump = repmat (Num, NM,1,1);
Nump = reshape(Nump, NM*NM,2);

Sign in to comment.

Accepted Answer

fbaillon
fbaillon on 4 Aug 2017
If you want to vectorize your problem, you can write something like this:
n=10;
m=n*n;
%
A=repmat(1:n,n*m,1);
B=repmat(1:n,m,n) ;
C=repmat((1:n),n*m,1);
nump=[A(:) B(:).*C(:)];
%
B=repmat(1:n,n,1)+repmat((1:n)',1,n);
C=repmat(1:n,n,1).*repmat((1:n)',1,n);
denmp=[ones(m*m,1) repmat(B(:),m,1) repmat(C(:),m,1)];
Maybe we can make it even faster...
Fabien Baillon.
  1 Comment
Jan
Jan on 4 Aug 2017
Since Matlab 2016b you can replace e.g.
C = repmat(1:n,n,1).*repmat((1:n)',1,n);
by
C = (1:n) .* (1:n)';
In older versions:
C = bsxfun(@times, 1:n, (1:n).');

Sign in to comment.

More Answers (2)

Andrei Bobrov
Andrei Bobrov on 4 Aug 2017
Edited: Andrei Bobrov on 4 Aug 2017
[c,b,a,k] = ndgrid(1:10);
nump = [k(:), a(:).*k(:)];
denmp = [ones(numel(k),1), b(:)+c(:), b(:).*c(:)];
  1 Comment
KL
KL on 4 Aug 2017
Edited: KL on 4 Aug 2017
Great one, voted! I need to get myself comfortable with ndgrid

Sign in to comment.


KL
KL on 4 Aug 2017
Edited: KL on 4 Aug 2017
c = 1:10;
c1 = reshape(repmat(c,1000,1),[10000,1]);
c2 = reshape(repmat(c,100,10),[10000,1]);
nump1 = [c1, c1.*c2];
dc2 = repmat(cell2mat(arrayfun(@(a,b) a:b, 2:11,11:20, 'UniformOutput', false)),1,100)';
dc3 = repmat(cell2mat(arrayfun(@(a,b,s) a:s:b, c,10:10:100,c, 'UniformOutput', false)),1,100)';
denmp1 = [ones(10000,1), dc2, dc3];
isequal(nump,nump1)
isequal(denmp,denmp1)

Categories

Find more on External Language Interfaces in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!