Build huge matrix with vector components

1 回表示 (過去 30 日間)
Kevin
Kevin 2014 年 7 月 10 日
コメント済み: Kevin 2014 年 7 月 11 日
how can I avoid double for in matlab in order to build matrices like this code do:
pos=[0 0];
for i=1:m;
for j=1:n;
pos=[pos; i j];
end
end
m and n are numbers like 500 and 900.
I have to find a better solution in order improve computation time . Thank you so much
Vins

採用された回答

Jos (10584)
Jos (10584) 2014 年 7 月 11 日
n = 4 % a small example
m = 3
[a, b] = ndgrid(1:n,1:m)
pos = [0 0 ; b(:) a(:)]
  1 件のコメント
Kevin
Kevin 2014 年 7 月 11 日
Thank you so much! This is great!

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

その他の回答 (2 件)

James Tursa
James Tursa 2014 年 7 月 11 日
編集済み: James Tursa 2014 年 7 月 11 日
One way:
c1 = ones(n,1)*(1:m);
c2 = (1:n)'*ones(1,m);
pos = [0 0; c1(:) c2(:)];
Or a similar method using repmat:
c1 = repmat(1:m,n,1);
c2 = repmat((1:n)',1,m);
pos = [0 0; c1(:) c2(:)];
You could have dramatically decreased the run time of your double loop simply by pre-allocating pos. E.g.,
pos = zeros(m*n+1,2);
k = 1;
for i=1:m;
for j=1:n;
k = k + 1;
pos(k,:) = [i j];
end
end
  1 件のコメント
Kevin
Kevin 2014 年 7 月 11 日
Thanks a lot! Really helpfull tips!

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


Image Analyst
Image Analyst 2014 年 7 月 11 日
You don't have to use double. You can use int16 if you want
for i = uint16(1:500)
and so on. It will be one 8th the size, though a 450,000 by 2 array is far from "huge". That's like 7 MB if it's double and less than 2 MB if uint16. Do you know how big an ordinary run of the mill point and shoot camera's digital image is? It's way bigger than that!

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by