Extracting values from array separated by zeros

5 ビュー (過去 30 日間)
Tereza Janatova
Tereza Janatova 2022 年 2 月 3 日
回答済み: Stephen23 2022 年 2 月 4 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by