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.
  댓글 수: 2
tengteng QQ
tengteng QQ 2021년 12월 6일
thank you for your help!! I really appreciative it!!
Matt J
Matt J 2021년 12월 6일
You're welcome, but please Accept-click the answer if it solved your problem.

댓글을 달려면 로그인하십시오.

추가 답변 (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