I have this code, where 'data' changes its size with every loop and has to be divided into four equal segments. This division has to be stored in variable 'epoch'. storing it in cell variable isn't an option. How can I store differen lengths of data?

 Accepted Answer

epoch = reshape(signal, [], 4).'
No need for a loop.

6 Comments

I tried the line above, got an error
Error using reshape
Product of known dimensions, 4, not divisible into total number of elements, 39505.
Here signal = 1x39505 double
has to be divided into four equal segments
signal = 1x39505 double
How do you divide a non multiple of four into 4 equal integral parts? Matlab is rightfully complaining that it isn't possible.
Then, what is the right way to divide 'signal' of any arbitraty length into four parts?
  • you can remove elements (from the end? beginning?) until the length is multiple of 4
  • you can add elements (to the end? beginning?) (0? nan? inf?) until the length is multiple of 4
  • you can split into 4 unequal parts but in this case you'll have to use a cell array
  • you can resample your signal to make it a length multiple of 4
Thanks for stating all the possible options. For my requirement, I would go for "splitting into four equal parts using a cell array", for which I have tried following:
epochs{1} = e;
epochs{2} = signal(1+(e-1)*seg:e*seg);
Then I have following error:
Unable to perform assignment because brace indexing is not supported for variables of this type.
You get this error because you're reusing epoch that you previously created as a double array. You would have avoided this problem if you had preallocated epoch before the loop. It's always a good to preallocate arrays that you're assigning to in a loop. It makes the loop faster, and avoids this type of errors:
epoch = cell(1, 4); %preallocate epoch
for .... your loop as normal
As usual for matlab, there's no need for the loop (and the preallocation):
defaultlength = ceil(numel(signal) / 4);
epoch = mat2cell(signal, 1, [ones(1, 3) * defaultlength, defaultlength + mod(defaultlength, -4)])
The last element of epoch will be up to 3 elements shorter than the previous 3.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!