How to change the value of the certain elements in a matrix

4 ビュー (過去 30 日間)
Omer hakan Yaran
Omer hakan Yaran 2022 年 6 月 20 日
コメント済み: Omer hakan Yaran 2022 年 6 月 20 日
Hi all, I want to change elements in an array inside of a matrix. I want all the elements that are less than 5 to be 0. For example
example = 4 8
7 2
2 9
5 3
I want this matrix to be:
0 8
7 2
0 9
5 3

採用された回答

Hernia Baby
Hernia Baby 2022 年 6 月 20 日
編集済み: Hernia Baby 2022 年 6 月 20 日
example = [4 8;7 2;2 9;5 3]
example = 4×2
4 8 7 2 2 9 5 3
idx = example(:,1) < 5
idx = 4×1 logical array
1 0 1 0
example(idx) = 0
example = 4×2
0 8 7 2 0 9 5 3
If you want to change all elements which is less than 5 to 0,
example = [4 8;7 2;2 9;5 3];
idx = example < 5
idx = 4×2 logical array
1 0 0 1 1 0 0 1
example(idx) = 0
example = 4×2
0 8 7 0 0 9 5 0
  1 件のコメント
Omer hakan Yaran
Omer hakan Yaran 2022 年 6 月 20 日
Thanks for the answer Hernia! It solved the problem.

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 6 月 20 日
example = [4 8
7 2
2 9
5 3];
mask = example < 5;
example(mask) = 0
example = 4×2
0 8 7 0 0 9 5 0
I'm not sure why one of the 2's stayed in your example (since it's less than 5) but to keep all the 2's, you'd do
example = [4 8
7 2
2 9
5 3];
mask = example < 5 & example > 2;
example(mask) = 0
example = 4×2
0 8 7 2 2 9 5 0
Of course you could do it all in one line of code if you combine things:
example(example < 5 & example > 2) = 0;

カテゴリ

Find more on Matrices and Arrays in Help Center and File Exchange

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by