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

4 ビュー (過去 30 日間)
tengteng QQ
tengteng QQ 2021 年 12 月 5 日
コメント済み: Matt J 2021 年 12 月 6 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by