Extracting values from array separated by zeros

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

回答(3 个)

David Hill
David Hill 2022-2-3
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 个评论
Tereza Janatova
Tereza Janatova 2022-2-3
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 2022-2-3
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
Image Analyst 2022-2-4
编辑:Image Analyst 2022-2-4
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 2022-2-4
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]}

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by