Create and fill cell array with differntly sized arrays within a function
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Carina Ufer
am 24 Feb. 2021
Kommentiert: Adam Danz
am 3 Mär. 2021
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 Kommentare
Adam Danz
am 3 Mär. 2021
If all of the sub-vectors are the same length, cellmat should work. What problems were you having with it?
Akzeptierte Antwort
Adam Danz
am 3 Mär. 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
- data is a vector
- 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)
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!