Storing blocks of matrix data into a cell array

1 次查看(过去 30 天)
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
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

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by