Delete items from array and split it up into new arrays
이전 댓글 표시
Hi,
I have a long array consisting of a long section of negative values, then a long section of positive values, then a long section of negative values and so on. I would like to remove all the negative values from my array, but at the same time split up the array into the individual long sections of positive values.
Simplified example:
array = [-0.0016 -0.0017 0.1746 0.1834 -0.0017 -0.0018 0.1567 0.1456 0.1744 -0.0018 -0.0017 0.1243 0.1456]
And then I would like this:
answer = {0.1746 0.1834} {0.1567 0.1456 0.1744} {0.1243 0.1456}
So the negative values has been removed, and the array is split up into new arrays containing the positive values from each section.
I hope it makes sense!
채택된 답변
추가 답변 (2개)
array = [-0.0016 -0.0017 0.1746 0.1834 -0.0017 -0.0018 0.1567 0.1456 0.1744 -0.0018 -0.0017 0.1243 0.1456];
is_negative = array < 0
start_idx = strfind([true is_negative],[true false])
end_idx = strfind([is_negative true],[false true])
answer = arrayfun(@(s,e)array(s:e),start_idx,end_idx,'UniformOutput',false)
You may find the code below doing the desired task
array = [-0.0016 -0.0017 0.1746 0.1834 -0.0017 -0.0018 0.1567 0.1456 0.1744 -0.0018 -0.0017 0.1243 0.1456]'
% find the mask where the array is non-negative
binMask = array >= 0;
% Find the start and end index of each region of interest
sidx = find(diff(binMask) == 1)+1
eidx = find(diff(binMask) == -1)
if (binMask(1) == 1)
sidx = [1;sidx];
end
if (binMask(end) == 1)
eidx = [eidx; length(array)];
end
% Split it into cells
ncell = min(length(sidx),length(eidx));
A = cell(ncell,1);
for i = 1:ncell
A{i} = array(sidx(i):eidx(i));
end
A
You can also achieve this task using the functions sigrangebinmask and binmask2sigroi.
댓글 수: 3
AH
2022년 11월 10일
Here is the code using sigrangebinmask and binmask2sigroi
% Find mask
threshold = 0; % split array into negative and non-negative parts
l = sigrangebinmask(array,threshold)
roilims = binmask2sigroi(l)
sidx = roilims(:,1) % beginning index
eidx = roilims(:,2) % ending index
ncel = size(roilims,1)
Bjælle
2022년 11월 10일
Image Analyst
2022년 11월 10일
@AH, what toolbox is sigrangebinmask in? It's not in the Signal Processing Toolbox.
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!