A doubt regarding a simple For loop indexing for certain rows only.
Mostrar comentarios más antiguos
Hi,
I have a matrix 'a' and I want to index only certain rows and delete them. Refer to code below.
Logic : when I reach the row starting point A or starting point B, I want to delete the following rows which contain the value [1 2 4 5]. I need to delete only those which come below either starting point A or B, also, the number of times [1 2 4 5] repeat is not fixed. If you observe, even after the 11th row [1 2 3 7] there are values [1 2 4 5] present but I want to retain them.
Any suggestions would be of great help, thank you. :)
a = 1 2 3 4 % start point A
1 2 4 5 % delete
1 2 4 5 % delete
1 2 4 5 % delete
1 2 4 5 % delete
1 2 3 5 % don't delete
1 2 3 6 % start point B
1 2 4 5 % delete
1 2 4 5 % delete
1 2 3 5 % don't delete
1 2 3 7 % don't delete anything from below here.
1 2 4 5
1 2 4 5
1 2 4 5
1 2 4 5
1 2 3 5
b = size(a,1);
for c = 1:b
if a(c, [1:4]) == [1, 2, 3, 4] | [1, 2, 3, 6]
for d = c+1:b
if (a(d, [1:4]) == [1, 2, 4, 5])
a(d, 5) = 1;
end
end
end
end
% displaying the numbers except for the ones that have 1 in their last column, basically deleting the rows with 1 in their last column
z = a(:, end);
y = a(~(z == 2), :);
y(:, end) = []
%% The result I'm obtaining from the above code :
y = 1 2 3 4
1 2 3 5
1 2 3 6
1 2 3 5
1 2 3 7
1 2 3 5
%% My expected output :
y = 1 2 3 4
1 2 3 5
1 2 3 6
1 2 3 5
1 2 3 7
1 2 4 5
1 2 4 5
1 2 4 5
1 2 4 5
1 2 3 5
Respuesta aceptada
Más respuestas (2)
Andrei Bobrov
el 2 de Ag. de 2019
lo = a(:,3) == 4;
ii = cumsum([0;diff(lo) == 1]).*lo;
m = max(ii);
ii(ii == 0) = m + 1;
out = a(ii >= m,:);
1 comentario
abhisrisai
el 2 de Ag. de 2019
Mariano
el 2 de Ag. de 2019
a = [1 2 3 4 % start point A
1 2 4 5 % delete
1 2 4 5 % delete
1 2 4 5 % delete
1 2 4 5 % delete
1 2 3 5 % don't delete
1 2 3 6 % start point B
1 2 4 5 % delete
1 2 4 5 % delete
1 2 3 5 % don't delete
1 2 3 7 % don't delete anything from below here.
1 2 4 5
1 2 4 5
1 2 4 5
1 2 4 5
1 2 3 5];
sp = find(ismember(a(:,4),[4,6])); % Find starting points
ep = find(ismember(a(:,4),[6,7])); % Find end points
n = length(ep); % How many? (assume number staring points = number
% end points)
dp = find(a(:,4)==5); % Candidates to be deleted
dr=[]; % DOES SOMEONE KNOW HOW TO VECTORIZE NEXT LOOP?
for j = 1:n
dr = [dr(:);dp(dp>sp(j)&dp<ep(j)-1)]; % Only delete rows between
% starting and end points
% Do not delete immediately
% before end point
end
a(dr,:)=[]
1 comentario
abhisrisai
el 2 de Ag. de 2019
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!