Extracting values from array separated by zeros

3 views (last 30 days)
Hi,
would like to ask if anybody has a hint on how to approach this situation. Basically, I have a big array of numbers (2000+), in which I have 12 sets of numbers that I am interested in, and the rest of the values are set to 0. What I would preferably like to do is to get each of these sets in a separate array, or at least a different column of a new array.
To show an example of what I mean.. array = 0 0 0 0 0 2 3 4 5 0 0 0 0 0 1 1 2 3 0 0 0 0 0 0 4 5 1 2 0 0 0 0 ....
to get final_array = 2 1 4
3 1 5
4 2 1
5 3 2
Thank you for any input.

Answers (3)

David Hill
David Hill on 3 Feb 2022
yourArray = [0 0 0 0 0 2 3 4 5 0 0 0 0 0 1 1 2 3 0 0 0 0 0 0 4 5 1 2 0 0 0 0];
newMatrix=reshape(yourArray(yourArray~=0),4,[]);
  2 Comments
Tereza Janatova
Tereza Janatova on 3 Feb 2022
I tried that, however, I get an error in the reshape function as the product of known dimension is not divisible into total number of elements..
David Hill
David Hill on 3 Feb 2022
Need a cell array because the number lengths are different sizes.
yourArray = [0 0 0 0 0 2 3 4 5 0 0 0 0 0 1 1 2 3 0 0 0 0 0 0 4 5 1 2 0 0 0 0];
s=num2str(yourArray~=0);
s=s(s~=' ');
b=regexp(s,'1*');
e=regexp(s,'1*','end');
for k=1:length(b)
yourCell{k}=yourArray(b(k):e(k));
end

Sign in to comment.


Image Analyst
Image Analyst on 4 Feb 2022
Edited: Image Analyst on 4 Feb 2022
If you know for a fact that all sets of numbers are of the same length, you can use regionprops() in the Image Processing Toolbox:
array = [0 0 0 0 0 2 3 4 5 0 0 0 0 0 1 1 2 3 0 0 0 0 0 0 4 5 1 2 0 0 0 0];
props = regionprops(array ~= 0, array, 'PixelValues');
output = vertcat(props.PixelValues)'
output = 4×3
2 1 4 3 1 5 4 2 1 5 3 2
If they have different lengths then you'll have to put them into a cell array or else pad some of the columns with zeros or some other value:
array = [0 0 0 0 0 2 3 4 5 0 0 0 0 0 1 2 3 0 0 0 0 0 0 4 5 1 2 9 0 0 0 0];
props = regionprops(array ~= 0, array, 'PixelValues');
for k = 1 : length(props)
ca{k} = props(k).PixelValues;
end
celldisp(ca)
ca{1} = 2 3 4 5 ca{2} = 1 2 3 ca{3} = 4 5 1 2 9

Stephen23
Stephen23 on 4 Feb 2022
V = [0,0,0,0,0,2,3,4,5,0,0,0,0,0,1,1,2,3,0,0,0,0,0,0,4,5,1,2,0,0,0,0];
D = diff([true,V==0,true]);
B = find(D<0);
E = find(D>0)-1;
C = arrayfun(@(b,e)V(b:e),B,E,'uni',0)
C = 1×3 cell array
{[2 3 4 5]} {[1 1 2 3]} {[4 5 1 2]}

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!