how to vectorize these "for loop" ?
조회 수: 1 (최근 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
2017년 8월 4일
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
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
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
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
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)
댓글 수: 0
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!