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

2 views (last 30 days)
Hi,
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);
end
Because I need to repeat this many times I wanted to outsource it to a function 'splitBlocks'
function cellArrayOfBlocks = splitBlocksEEG(data)
end
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);
end
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!
  4 Comments
Carina Ufer
Carina Ufer on 3 Mar 2021
Edited: Carina Ufer on 3 Mar 2021
The input is just continuous data which needs to be separated into blocks. The beginning and the end of each block that needs to be extracted is saved in a variable in the workspace. To access it within the function I used evalin.
For example the first block is from the continuousData(17000:18000) where startInx(1) = 17000 and endInx(1) = 18000.
This data should be saved in a cell of the 240x1 cell array.
It works without wraping it in a function.
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)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!