フィルターのクリア

Faster method of creating list of looped row vectors?

1 回表示 (過去 30 日間)
mfas
mfas 2015 年 7 月 6 日
コメント済み: mfas 2015 年 7 月 6 日
At the moment I have the following code:
kres=1;
kz=0;
K=[];
for kx=-3:kres:3
for ky=-3:kres:3
k=[kx,ky,kz];
K=[K;k];
end
end
to achieve a list of row vectors in the form:
[-3,-3,0;-3,-2,0;-3,-1,0;-3,0,0;....;3,2,0;3,3,0]
However when kres is reduced to < 0.01 this loop takes a long time to compute. Is there a faster way to achieve the same result without having to have a loop within a loop?

採用された回答

Bjorn Gustavsson
Bjorn Gustavsson 2015 年 7 月 6 日
kres=1; kz=0; K=[]; This is the way I'd go about it:
x = -3:kres:3;
y = -3:kres:3;
z = 0;
[x,y,z] = meshgrid(x,y,z);
K = [x(:),y(:),z(:)];
HTH
  1 件のコメント
mfas
mfas 2015 年 7 月 6 日
That's perfect thanks!

サインインしてコメントする。

その他の回答 (2 件)

Keith Hooks
Keith Hooks 2015 年 7 月 6 日
You'll see quite a bit of improvement if you pre-allocate K. I understand the coding is not as clean, but the speed improvement is close to 5X for the 0.1 resolution.
Original: Elapsed time is 0.027472 seconds .
With pre-allocation: Elapsed time is 0.005479 seconds .
kres=.1;
kz=0;
kx = -3:kres:3;
ky = -3:kres:3;
n = length(kx);
m = length(ky);
K=zeros(n*m,3);
for i=1:n
for j=1:m
k=[kx(i),ky(j),kz];
K((i-1)*n + j,:) = k;
end
end

Thorsten
Thorsten 2015 年 7 月 6 日
編集済み: Thorsten 2015 年 7 月 6 日
kres=0.01;
kx = -3:kres:3;
N = numel(kx);
k1 = repmat(kx, [N 1]);
K2 = [k1(:) repmat(kx', [N 1]) repmat(0, [N^2 1])];

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by