Remove value question: if previous row -row>+-3, then remove the row in matrix A

1 visualización (últimos 30 días)
Hi, I am a beginner at coding. I would like to know why did my code is not working. I have a matrix A, I would like to subtract every two rows for all my rows in the same matrix, and if the subtract >+-3, then remove the row.
A = [1;9;5;4;3;6;764;465;6;8;7;5;3;6;8;8;56;6;4;3;6;8;2;4;6;8;9;22;4]
example:
if row(2,1)-row(1,1)>(+-3) then I want to remove row(1,1) in matrix A
i try to code this:
A = [1;9;5;4;3;6;764;465;6;8;7;5;3;6;8;8;56;6;4;3;6;8;2;4;6;8;9;22;4]
for j = 1:size(A)
if A(j+1,1)-A(j,1)>+-3
A(j,1)=[]
end
end
However, it is not working...please help me confirm the following information. I am appreciative of your help!!

Respuesta aceptada

Matt J
Matt J el 5 de Dic. de 2021
Editada: Matt J el 5 de Dic. de 2021
A(diff(A)>-3)=[]
or
A(abs(diff(A))<3)=[];
if that's what you really meant.
  2 comentarios
tengteng QQ
tengteng QQ el 6 de Dic. de 2021
thank you for your help!! I really appreciative it!!
Matt J
Matt J el 6 de Dic. de 2021
You're welcome, but please Accept-click the answer if it solved your problem.

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 5 de Dic. de 2021
Your code contains some problems:
  • for j = 1:size(A)
Remember, that size() replies a vector containing the size of all dimensions. In the expression 1:size(A) only the first element of size(A) is used. Better:
for j = 1:numel(A) % or size(A, 1)
A 2nd problem: You check A(j+1). Then j is not allowed to be numel(A), but the loop must stop one element before.
  • if A(j+1,1)-A(j,1)>+-3
The expression "+-" is not defined in Matlab. I assume you want:
if abs(A(j+1,1) - A(j,1)) > 3
  • A(j,1)=[]
After you have deleted one element, the original array is shorter. Then the loop must fail, because elements after the last one are tested.
I assume you want:
A = [1;9;5;4;3;6;764;465;6;8;7;5;3;6;8;8;56;6;4;3;6;8;2;4;6;8;9;22;4]
delete = false(size(A));
for j = 1:numel(A) - 1
delete(j + 1) = abs(A(j+1,1) - A(j,1)) > 3;
end
A(delete) = [];

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by