Extracting values from array separated by zeros
3 views (last 30 days)
Show older comments
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.
0 Comments
Answers (3)
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
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
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)'
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)
0 Comments
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)
0 Comments
See Also
Categories
Find more on Matrix Indexing 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!