Storing blocks of matrix data into a cell array

조회 수: 2 (최근 30일)
Harry
Harry 2015년 6월 17일
편집: Alfonso Nieto-Castanon 2015년 6월 17일
I have a 2-D array, with discrete blocks of data in and amongst zeros. My data is the following:
0 0
0 0
0 0
3 9
4 10
5 11
6 12
0 0
0 0
0 0
0 0
7 9.7
8 9.8
9 9.9
0 0
0 0
A block of data is defined as contiguous set of data, without interruptions of a [0 0] row. So in this example, the 1st block of data would be:
3 9
4 10
5 11
6 12
And 2nd block is
7 9.7
8 9.8
9 9.9
I would like to loop through this array and store the chunks of data into a cell array.
The reason I want to use a cell array is that I do not know how big each chunk of data will be (they will be 2 columns, but the number of rows is variable).
My question is that I do not know how long my original array is going to be, so is there any such thing as dynamic memory allocation in MatLab like there is in C?
Can anyone point me in the right direction with an algorithm (or pseudo-algorithm) for me to store data in the cell array?
I'd rather not overcomplicate things by using dynamic memory allocation.

채택된 답변

Alfonso Nieto-Castanon
Alfonso Nieto-Castanon 2015년 6월 17일
편집: Alfonso Nieto-Castanon 2015년 6월 17일
You may use mat2cell for that. For example:
rows = find(any(X,2));
blocklengths = diff(find([1;diff(rows)>1;1]));
blocks = mat2cell(X(rows,:),blocklengths);

추가 답변 (1개)

Walter Roberson
Walter Roberson 2015년 6월 17일
편집: Walter Roberson 2015년 6월 17일
Yes. If you assign to a location past the end of the existing array then the array will grow to fit. So for example,
blocks = {};
P = 1;
while P <= size(TheMatrix,1)
... find a block between P and Q
blocks{end+1} = TheMatrix(P:Q,:);
P = Q + 1;
end
By the way:
tf = ismember([0 0], TheMatrix, 'rows');
starts = strfind([true tf], [true false]);
ends = strfind([tf true], [false true]);
blocks = cell(length(starts));
for K = 1 : length(starts)
blocks{K} = TheMatrix(starts(K):ends(K), :);
end

Community Treasure Hunt

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

Start Hunting!

Translated by