Create and fill cell array with differntly sized arrays within a function

6 views (last 30 days)
I wanted to write a function because because I need to extract blocks within a range from continous data. Thereby each block has a different length e.g. 1x20. First I implmented it as following
complete_block = cell(numel(x),1);
for i = 1:numel(start)
startInx = start(i);
endInx = ending(i);
complete_block{i} = data(start:ending);
Because I need to repeat this many times I wanted to outsource it to a function 'splitBlocks'
function cellArrayOfBlocks = splitBlocksEEG(data)
max = int8((numel( evalin('base', 'x'))))
start = evalin('base', 'start'); % size 240x1
ending = evalin('base', 'ending'); % get variable from current workspace
cellArrayOfBlocks = cell(max,1);
for i = 1:numel(start)
startInx = int8(start(i)); % is type double, cast to integer
endInx = int8(ending(i));
cellArrayOfBlocks{i} = data(startInx:endInx);
However I won't get the 240x1 cell array containing 1xN data. I tried to use cellmat to implement the cell array but I was not successfull. I thought that the error could be that the data is not an integer but that didn't solve the problem neither. Why is the mode of operation different within a function? Why can't I just write the same code in a function and get the same output?
I know that it is not a recommended structure to manage data, but I also do not know any better way.
Thank you for any advice in advance!
Adam Danz
Adam Danz on 3 Mar 2021
If all of the sub-vectors are the same length, cellmat should work. What problems were you having with it?

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 3 Mar 2021
The size and shape of data you're working with is not clear but I'm guessing from the first for-loop in your question that
  1. data is a vector
  2. startIdx & endIdx are vectors of indices
If that is correct, you just need this one line of code.
data = 1:100;
startIdx = [1 10 35 70];
endIdx = [9 34 69 100];
C = arrayfun(@(i,j){data(i:j)},startIdx,endIdx)
C = 1x4 cell array
{1×9 double} {1×25 double} {1×35 double} {1×31 double}

More Answers (0)




Community Treasure Hunt

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

Start Hunting!