How to split or divide a larger array in to the predetermined size?

My original array is only one dimensional of ordeer 1*15000 and 90% of it consisting zeroes. I want to create smaller arrays where there is non zero values and store them in different array. For example if my original array is [0,0,0,0,6,8,6,0,0,0,0,0,8,8,7,6,87,6,0,0,0] then I want it to split in [6,8,6] and [8,8,7,6,87,6].
I wrote the code to determine the starting and ending position of the non zero element but it is lengthy. Is there any other way?

 Accepted Answer

You can use accumarray to put contiguous groups of non-zeros into one cell array:
>> vec = [0,0,0,0,6,8,6,0,0,0,0,0,8,8,7,6,87,6,0,0,0];
>> idx = vec(:)>0;
>> idy = cumsum(diff([0;idx])>0);
>> out = accumarray(idy(idx),vec(idx),[],@(n){n});
>> out{:}
ans =
6
8
6
ans =
8
8
7
6
87
6

4 Comments

@stephen
thank you but i need to store them in an array so that i can operate on them letter, how can i do that? also i was using
sigmask = a>0; signal_start_positions = strfind(sigmask, [0 1]); signal_end_positions = strfind(sigmask, [1 0]);
it was lengthy.
@kedar Paul: a cell array is, as its name implies, an array. So the output I gave you is an array already.
If you want to store those values in a numeric array then you need to observe that the number of elements in each group is different, so you can either:
1. Join them together int one vector:
>> vertcat(out{:})
ans =
6
8
6
8
8
7
6
87
6
2. downlaod a FEX submission that concatenates unequal length numeric arrays within a cell array into one numeric array.
Personally I wouldn't bother: keeping the data in a cell array is convenient enough already:
>> out{2}
ans =
8
8
7
6
87
6
@stephen sorry I was not clear, I mean that I want to store the data in matrix form so that I can perform different statistical operation using a for loop. I hope I made myself clear now.
It is very simple to loop over the contents of the cell array directly:
for k = 1:numel(out)
out{k}
end
However if you really want to merge the contents of the cell array back into one numeric array then you will need to use option 2, such as padcat:
padcat(out{:})

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!