Vectorizing a nasted loop
Show older comments
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 Comments
Jos (10584)
on 1 May 2019
Did you preallocate the two output arrays? That should speed things up considerably.
Add this before the loop:
Datachunk = zeros(Window, Chunk)
Oded T
on 2 May 2019
Accepted Answer
More Answers (1)
Guillaume
on 1 May 2019
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 Comments
Rik
on 1 May 2019
It also assumes the size of both is Window*Chunks (and my solution assumes they are at least that size, but so does the original code).
Guillaume
on 2 May 2019
Yes, of course. There is a lot of information missing in the question.
To Oded, if numel(Raw.RAW) > Window*Chunks, you should use Rik's solution. If numel(Raw.RAW) == Window*Chunks, you should use mine as it's simpler in that case.
Guillaume
on 2 May 2019
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?
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!