How to remove the number 0 between index1 & index2 ?

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

采纳的回答

Alberto Cuadra Lara
Hi Seungkuk,
There you have it. The tricky thing here is that you have to create a vector of the same length as your input, whose values are zero or one if it satisfies both conditions or not, respectively.
% Inputs
A0 = [0 0 0 1 1 1 1 0 0 0 2 2 1 0 0 0 1 1 0 0 0];
ind_1 = 4;
ind_2 = length(A0) - 4;
loc_value = 0;
% Constants
A = A0;
N = length(A);
% Set range
range = ind_1:ind_2;
% Set condition
cond_1 = A == loc_value;
cond_2 = zeros(1, N);
for i = 1:N
if i >= ind_1 && i <= ind_2
cond_2(i) = 1; % Is in range
end
end
% Remove loc_value from index_1 to index_2
A(cond_1 & cond_2) = [];
% Result
A
A = 1×15
0 0 0 1 1 1 1 2 2 1 1 1 0 0 0
% Check
sol = [0 0 0 1 1 1 1 2 2 1 1 1 0 0 0];
isequal(A, sol)
ans = logical
1

更多回答(1 个)

DGM
DGM 2022-1-25
编辑:DGM 2022-1-25
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'
B = 1×15
0 0 0 1 1 1 1 2 2 1 1 1 0 0 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'
B = 1×15
0 0 0 1 1 1 3 2 2 1 9 1 0 0 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))]
D = 1×15
0 0 0 1 1 1 3 2 2 1 9 1 0 0 0

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by