I want to rounding selected data with Looping and If else

조회 수: 5 (최근 30일)
Michael Andersen
Michael Andersen 2023년 5월 8일
댓글: Stephen23 2023년 5월 9일
I have workspace variable "a" which there is a 510x1 matrix data inside like this
I want to change cell containing 10+ only (like 10.0299, 10.0419, 10.0064,.......) change to be 10.0000. And this is my program code and I use rounding function to make 10,+ data change to be 10.0000
n=length(a);
for i=1:n
if(a > 0 & a < 10)
v=(round(a,0))
else
v=a
end
end
After I run the program, there is no change on "a" data (still like that picture), and if I switch "v=(round(a,0))" and "v=a" position and run it, all data in matrix are rounded like 9.0000; 10,0000;....... what's wrong with my code? thank you
  댓글 수: 1
Stephen23
Stephen23 2023년 5월 9일
" want to change cell containing 10+ only (like 10.0299, 10.0419, 10.0064,.......) change to be 10.0000"
The very simple and very efficient MATLAB approach:
a = min(10,a)
Any other code you can come up with will be slower and more complex than that.

댓글을 달려면 로그인하십시오.

답변 (2개)

DGM
DGM 2023년 5월 8일
편집: DGM 2023년 5월 8일
It's not really clear what the desired conditions are.
If what you want is to constrain values to the interval [0 10], you can do that like so:
A = [-1.2 1.2 8.5 12.5];
% using min(max())
B = min(max(A,0),10)
B = 1×4
0 1.2000 8.5000 10.0000
% or using imclamp() (attached)
B = imclamp(A,[0 10])
B = 1×4
0 1.2000 8.5000 10.0000
This keeps values inside the interval unchanged.
Both of these examples do the same thing. The only difference is that the latter is easier to read and less prone to mistakes.
If you only need a one-sided constraint, you can use min() by itself

VBBV
VBBV 2023년 5월 8일
편집: VBBV 2023년 5월 9일
a = rand(1)*randi([5 25],510,1)
a = 510×1
5.4417 18.1391 18.1391 9.0696 8.1626 7.2557 10.8835 14.5113 16.3252 17.2322
n=length(a);
for i=1:n
if(a(i) > 0 & a(i) < 10)
a(i) = a(i);
else
a(i) = round(a(i),0);
end
end
a
a = 510×1
5.4417 18.0000 18.0000 9.0696 8.1626 7.2557 11.0000 15.0000 16.0000 17.0000
Use the round function shown as above.
  댓글 수: 1
VBBV
VBBV 2023년 5월 8일
Also, when you use a directly in the if-else condition , it refers to all elements in the vector at once.
You need to access individual elements one by one and then round them

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by