How to replace matrix elements by using statements?
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
更多回答(1 个)
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!