How to remove the number 0 between index1 & index2 ?
Show older comments
I would like to remove the number 0 between index1 & index2.
How can I remove it....
The result I want is A = [0 0 0 1 1 1 1 2 2 1 1 1 0 0 0];
clear all; clc; close all;
A = [0 0 0 1 1 1 1 0 0 0 2 2 1 0 0 0 1 1 0 0 0];
index1 = find(A > 0,1,'first');
index2 = find(A > 0,1,'last');
ind3 = find(A==0);
A(index1<ind3 & ind3<index2) = []; % It provides me the wrong output.
Accepted Answer
More Answers (1)
Assuming that you're only concerned with zeros between 1 or 2, and that all values are single-digit numbers, here's one way:
A = [0 0 0 1 1 1 1 0 0 0 2 2 1 0 0 0 1 1 0 0 0];
B = regexprep(char(A+'0'),'(?<=[1|2])0+(?=[1|2])','')-'0'
If you want any nonzero digits to be considered:
A = [0 0 0 1 1 1 3 0 0 0 2 2 1 0 0 0 9 1 0 0 0];
B = regexprep(char(A+'0'),'(?<=[1-9])0+(?=[1-9])','')-'0'
If the numbers aren't single-digit and you want to get rid of zeros between any nonzero numbers, this is a different way:
idx1 = find(A ~= 0,1,'first');
idx2 = find(A ~= 0,1,'last');
D = A(idx1:idx2);
D = [max(A(1:idx1-1),0) D(D~=0) min(A(idx2+1:end),numel(A))]
Categories
Find more on Matrices and Arrays 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!