Extracting values from array separated by zeros
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (3)
David Hill
am 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 Kommentare
David Hill
am 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
am 4 Feb. 2022
Bearbeitet: Image Analyst
am 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 Kommentare
Stephen23
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!