how to vectorize these "for loop" ?

22 次查看(过去 30 天)
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 个评论
Christos Saragiotis
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);

请先登录,再进行评论。

采纳的回答

fbaillon
fbaillon 2017-8-4
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 个评论
Jan
Jan 2017-8-4
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).');

请先登录,再进行评论。

更多回答(2 个)

Andrei Bobrov
Andrei Bobrov 2017-8-4
编辑:Andrei Bobrov 2017-8-4
[c,b,a,k] = ndgrid(1:10);
nump = [k(:), a(:).*k(:)];
denmp = [ones(numel(k),1), b(:)+c(:), b(:).*c(:)];
  1 个评论
KL
KL 2017-8-4
编辑:KL 2017-8-4
Great one, voted! I need to get myself comfortable with ndgrid

请先登录,再进行评论。


KL
KL 2017-8-4
编辑:KL 2017-8-4
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)

类别

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