How to replace matrix elements by using statements?

6 ビュー (過去 30 日間)
Hasancan Saral
Hasancan Saral 2022 年 10 月 3 日
コメント済み: Hasancan Saral 2022 年 10 月 3 日
I have a matrix which has 9x9 size.(mhw1)
so i want to change the elements which higher than 3 to 3 and lower than 1 to 1.
what am i doing wrong?
c=zeros(size(mhw1));
for i = 1:size(mhw1)
if mhw1(i)>.3
c(i)=3;
elseif mhw1(i)<.1
c(i)=1;
end
end

採用された回答

KSSV
KSSV 2022 年 10 月 3 日
編集済み: KSSV 2022 年 10 月 3 日
It is very simple and straight forward. Consider this example.
A = rand(3) ;
A(A<0.3) = 0 ;
A(A>0.8) = 1 ;
  1 件のコメント
Hasancan Saral
Hasancan Saral 2022 年 10 月 3 日
Never thought it that way, that was on me.(forgot to think simple) Thanks for the answer.

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

その他の回答 (1 件)

Ergin Sezgin
Ergin Sezgin 2022 年 10 月 3 日
Hello Hasancan,
You should use both rows and columns in two for loops to check and adjust each element in a 2D matrix.
for i = 1:size(mhw1,1)
for j = 1:size(mhw1,2)
if mhw1(i,j) > 3
mhw1(i,j) = 3;
elseif mhw1(i,j) < 1
mhw1(i,j) = 1;
end
end
end
You can also perform it in a quicker and more efficient way:
mhw1(mhw1>3) = 3
mhw1(mhw1<1) = 1
I hope it helps.
  1 件のコメント
Hasancan Saral
Hasancan Saral 2022 年 10 月 3 日
Thanks for the answer, always forgetting to think simple :)

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

カテゴリ

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