How to code a generic for loop that removes a row with missing requirement

I am trying to create a generic program using a for loop that removes the row if a user checks their number against it and it is not there. A matrix will have unspecified number of rows and columns, a user will input their value say n, if the user's n is not in row k of A, row k should be deleted.
A = magic(50);
row = size(A,1);
n = 3; %or whatever number
for r = 1:1:row
if not(ismember(n, A)) %if n is not a member of whatever row it is on, it should be deleted
%what goes in here?
end
end

 採用された回答

Voss
Voss 2022 年 4 月 1 日
A = magic(50);
row = size(A,1);
n = 3; %or whatever number
rows_to_delete = [];
for r = 1:1:row
if ~ismember(n, A(r,:)) %if n is not a member of whatever row it is on, it should be deleted
rows_to_delete(end+1) = r;
end
end
% delete the rows
A(rows_to_delete,:) = [];

3 件のコメント

Voss
Voss 2022 年 4 月 1 日
Or, without the loop:
A = magic(50);
n = 3;
A(~any(A == n,2),:) = [];
Andromeda
Andromeda 2022 年 4 月 2 日
This is exactly what I was looking for, thank you!
Voss
Voss 2022 年 4 月 2 日
You're welcome!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2022 年 4 月 1 日

コメント済み:

2022 年 4 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by