Storing blocks of matrix data into a cell array
1 view (last 30 days)
Show older comments
Harry
on 17 Jun 2015
Edited: Alfonso Nieto-Castanon
on 17 Jun 2015
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.
0 Comments
Accepted Answer
Alfonso Nieto-Castanon
on 17 Jun 2015
Edited: Alfonso Nieto-Castanon
on 17 Jun 2015
rows = find(any(X,2));
blocklengths = diff(find([1;diff(rows)>1;1]));
blocks = mat2cell(X(rows,:),blocklengths);
0 Comments
More Answers (1)
Walter Roberson
on 17 Jun 2015
Edited: Walter Roberson
on 17 Jun 2015
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
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!