how to vectorize these "for loop" ?
Show older comments
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
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);
Accepted Answer
More Answers (2)
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
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 Loops and Conditional Statements 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!