Vectorizing a nasted loop
1 回表示 (過去 30 日間)
古いコメントを表示
hello,
I'm using a simple nasted loop for assignment:
for i=1:Chunks %loop for number of chunks
for n=1:Window
DataChunk(n,i) = Raw.RAW(idx); %for each itteration - take the right raw data into the right chunk
TimeChunk(n,i) = Raw.Time(idx);
idx = idx+1; % increment the indes
end
end
this loop takes forever for a very big amount of data,
anyome can please help me vectorize it ?
2 件のコメント
Jos (10584)
2019 年 5 月 1 日
Did you preallocate the two output arrays? That should speed things up considerably.
Add this before the loop:
Datachunk = zeros(Window, Chunk)
採用された回答
Rik
2019 年 5 月 1 日
This should work:
idx=reshape(1:(Chunks*Window),Window,Chunks);
DataChunk=Raw.RAW(idx);
TimeChunk=Raw.Time(idx);
The output should be the correct size, as it usually retains the shape of the index. If this is not the case, you can always use reshape to adjust the arrays to suit your needs.
If idx didn't start at 1 in your code, you can add the old value after the reshape.
4 件のコメント
Guillaume
2019 年 5 月 2 日
There's nothing mysterious about it. It's simply reshaping a vector/matrix in the desired shape (in your case a Window * Chunks array). The idx business is just in case your original matrix/vector is larger than the desired result, and simply crops the original array/matrix to the required number of elements.
If the original array/matrix has already the required number of elements, then you don't need to bother with idx. See my answer.
その他の回答 (1 件)
Guillaume
2019 年 5 月 1 日
DataChunk = reshape(Raw.RAW, Window, Chunks);
TimeChunk = reshape(Raw.Time, Window, Chunks);
That's assuming that RAW and Time are structure fields or object properties and not object methods.
5 件のコメント
Guillaume
2019 年 5 月 2 日
I think we need a bit more context to understand your question. It seems you want to divide some sampled data into chunks. Why? What are you going to do with it?
Reshaping the samples into a matrix has some advantages as matrix are easier to work with, but it forces you to have the same number of samples in each chunk, which by the sound of it may be a problem. What are you doing with the matrix afterward?
参考
カテゴリ
Help Center および File Exchange で Entering Commands についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!