フィルターのクリア

Set matrix element to zero for some condition

120 ビュー (過去 30 日間)
Philipp
Philipp 2023 年 6 月 1 日
コメント済み: Vilém Frynta 2023 年 6 月 1 日
Hello,
I'm new to Matlab and have a simple question. I have a matrix M of numbers and I like to create a new matrix, where all elements are set to zero that do not satisfy a certain condition (say, e.g., all elements larger than 1). How do I do this in the most efficient way?
I tried
filter = find((M<=1));
Mnew = M(filter);
but unfortunately it doesn't work because filter gives me a list of linear indices, but I like to keep the shape of the matrix M. I know that
[row,col] = find((M<=1));
gives me the row and column indices separately, but
Mnew = M([row,col]);
also does not do the job (I kind of understand that it does not work, but I have no idea how to fix it).
Any help is greatly appreciated!

採用された回答

Vilém Frynta
Vilém Frynta 2023 年 6 月 1 日
編集済み: Vilém Frynta 2023 年 6 月 1 日
Hi,
my approach would be as follows:
% Matrix 5x5 with random numbers 0-10
M = randi(10, 5)
M = 5×5
9 6 4 8 8 2 5 10 7 1 9 7 8 2 7 6 4 3 9 9 6 1 5 8 5
% Create logical vector of numbers higher than 5 (condition)
idx = M > 5;
% Apply it to your matrix and set those values to 0
M(idx) = 0
M = 5×5
0 0 4 0 0 2 5 0 0 1 0 0 0 2 0 0 4 3 0 0 0 1 5 0 5
Ultimately, you can do it in one line.
M(M>5)=0;
  2 件のコメント
Philipp
Philipp 2023 年 6 月 1 日
Oh, thanks lot. I expected there was a simple one-line answer, but I was unable to find it! :)
Vilém Frynta
Vilém Frynta 2023 年 6 月 1 日
Yes, in MATLAB, there's always simpler solution to the problem than you have. Almost always when I help people on this forum, someone better comes and does something I recommended much easier.
Happy I helped.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by