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

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

采纳的回答

Matt J
Matt J 2021-12-5
编辑:Matt J 2021-12-5
A(diff(A)>-3)=[]
or
A(abs(diff(A))<3)=[];
if that's what you really meant.

更多回答(1 个)

Jan
Jan 2021-12-5
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) = [];

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by