Basic Vectorization Question (speed required)

1 回表示 (過去 30 日間)
Matlab2010
Matlab2010 2013 年 11 月 22 日
コメント済み: Matlab2010 2013 年 11 月 22 日
I have a 2D matrix of data. I have an index to reduce that 2D matrix to a 1D matrix.
How can I do it without using a for loop? Ie by vectorization as it needs to be super quick.
thanks
Z = rand(5,100); %matrix of data
IDY = randi([1 5], [1,100]); %index into that matrix
X = NaN(size(Z,2),1); %pre allocate
X = Z(IDY,:); %this fails as it does not generate a 1D matrix (vector) as required
this is how I can do it using a loop
X2 = NaN(size(Z,2),1);
for i = 1: size(X,1)
X2(i) = Z(IDY(i),i);
end

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 22 日
Z = rand(5,100); %matrix of data
IDY = randi([1 5], [1,100]); %index into that matrix
X = NaN(size(Z,2),1); %pre allocate
X = Z(IDY,:)
X3=Z(sub2ind(size(Z),IDY,1:size(Z,2)))
  1 件のコメント
Matlab2010
Matlab2010 2013 年 11 月 22 日
thats a great answer. thank you!
PS have never used sub2ind before but will read up on it now

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2013 年 11 月 22 日
To get all of Z in row-major order, do:
X = Z(:);
To get random ordering, like your code attempted to do, try this:
Z = rand(5,100) %matrix of data
randomIndexes = randperm(numel(Z)) %index into that matrix
X = Z(randomIndexes)
  1 件のコメント
Matlab2010
Matlab2010 2013 年 11 月 22 日
編集済み: Matlab2010 2013 年 11 月 22 日
I must have explained my question very badly.
I have an index of size 1*T (in my example T = 100). Each value in the index can take a value 1: K (K = 5) in my example. This is an index value for each row in the K*T data matrix. I wish to apply the index to generate a matrix 1*T in size.
Your example code generates an index of values 1: K*T and then produces an a matrix of K*T in size.
thanks

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by