Extract subvectors from a vector without using loops

Hi, i'm trying to speed up my code and reduce loops in it. My problem is to extract some parts of a vector (original_vector) in new smaller vectors, or in a matrix where every columns is each one of those extracted vectors. So in a variable i have the original vector, and in an other one a "N x 2" matrix where in the first column is stored the start index of the "n-th" subvector to extract, and in the second one the end index of it. I need something faster to substitute the loop:
for k=1:(number_of_extractions) extracted(:,k)=original_vector(index(k,1):index(k,2)); end
P.S. every extracted vector as the same elements
Thanks!

2 件のコメント

Walter Roberson
Walter Roberson 2015 年 10 月 19 日
You refer to original_vector in your description but your code has two layers original(vector(range) ) ?
Niccoli Francesco
Niccoli Francesco 2015 年 10 月 19 日
sorry, wrong digit! The code was this:
for k=1:(number_of_extractions) extracted(:,k)=original_vector(index(k,1):index(k,2)); end

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

 採用された回答

Walter Roberson
Walter Roberson 2015 年 10 月 19 日

0 投票

d=index(2,1)-index(1,1);
extracted = original_vector(bsxfun(@plus, (0:d).', index(:, 1).')) ;

1 件のコメント

Niccoli Francesco
Niccoli Francesco 2015 年 10 月 19 日
Really thanks! I have a problem again, beacause with this kind of formulation it saves me sub_vectors of 1000 elements, but the sub_vectors dimension (definited by index(n,2)-index(n,1)) is different and equal to 90000

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

その他の回答 (1 件)

Guillaume
Guillaume 2015 年 10 月 19 日

0 投票

You can use mat2cell for this but I don't know if it's going to be any faster:
original_vector = 1:100; %demo data
index = [2 15; 30 10; 40 20; 79 5]; %demo data
divisions = [index(:, 1), sum(index, 2)]';
divisions = diff([1; divisions(:); numel(original_vector)+1]); %calculate length of each block
subvectors = mat2cell(original_vector, 1, divisions); %this includes spacer blocks (of possible length 0 between each wanted block
subvectors = subvectors(2:2:end); %get rid of 'spacer blocks'

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by