フィルターのクリア

how to vectorize these "for loop" ?

1 回表示 (過去 30 日間)
Anita pawar
Anita pawar 2017 年 8 月 4 日
編集済み: KL 2017 年 8 月 4 日
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
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
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 Center および File ExchangeExternal Language Interfaces についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by