Getting error while deleting every row of the matrix M that contains the variable x

1 回表示 (過去 30 日間)
I'm trying to write a function N = Deletevar(x,M) that returns a matrix N by deleting every row of the matrix M that contains the variable x.
My code is :
function N = Delete_var(x,M)
N = [];
[a,b] = size(M);
for i = 1:a
for j = 1:b
if M(i,j)== x
M(i,:)=[];
N = M;
end
end
end
end
However when i call Delete_var(3,[1,2,3;3,4,5;7,8,9]), I get:
Index in position 1 exceeds array bounds (must not exceed 2).
Error in Delete_var (line 9)
if M(i,j)== x
Why is that? How to solve the problem? Please help!
  2 件のコメント
David Fletcher
David Fletcher 2021 年 5 月 1 日
編集済み: David Fletcher 2021 年 5 月 1 日
The inherent problem you have with the logic of your code is that you are basing the for loops on the starting size of the array (M). Consider what happens when you delete a row in M - the row dimension becomes smaller, but this is not reflected in the for loop which is still based on the starting size of the array. The code will always ultimately throw an error (unless no rows are deleted) since there will be a mismatch between the starting size of M and its size after rows are deleted.
Ningze Xia
Ningze Xia 2021 年 5 月 1 日
Ohhhh I understand what you mean! Combined your comment and per isakson's answer I successfully solve the problem! Thank you for your help!

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

採用された回答

per isakson
per isakson 2021 年 5 月 1 日
編集済み: per isakson 2021 年 5 月 1 日
The trick is to iterate in reverse order, i.e a:-1:1 instead of 1:a. Try this
%%
M = magic(5);
x = 13;
N = Delete_var(x,M)
N = 4×5
17 24 1 8 15 23 5 7 14 16 10 12 19 21 3 11 18 25 2 9
%%
function N = Delete_var(x,M)
N = [];
[a,b] = size(M);
for i = a:-1:1
for j = b:-1:1
if M(i,j)== x
M(i,:)=[];
N = M;
end
end
end
end

その他の回答 (1 件)

Turlough Hughes
Turlough Hughes 2021 年 5 月 1 日
No need for any loops. Here's an example of data to work with
M = randi(10,[10 3]); % sample data
x = 3; % delete rows with this value
You can delete any rows in M containing x as follows:
M(any(M==x,2),:)=[];
  1 件のコメント
Ningze Xia
Ningze Xia 2021 年 5 月 1 日
Thank you for your answer! This is a new techinique for me and it's very useful! Really appreciate!

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

カテゴリ

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