Create and fill cell array with differntly sized arrays within a function
조회 수: 4 (최근 30일)
이전 댓글 표시
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
Adam Danz
2021년 3월 3일
If all of the sub-vectors are the same length, cellmat should work. What problems were you having with it?
채택된 답변
Adam Danz
2021년 3월 3일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!