rounding a column vector

조회 수: 16 (최근 30일)
Ankit Labh
Ankit Labh 2018년 8월 14일
댓글: Brent F 2021년 7월 23일
I have a column vector with 8000 entries around temp (see array below).
temp=[5 50 150 180 200 220 240 250 260 265 270 272 274 275 275.5 276 277 278 279 279.5 280 280.5 281 281.5 282 284 286 288 290 295 300 310 320]; %temperatures [K]
I did the rounding up to one decimal places. Now I have numbers like 273.9 and 274.1 along with 274. I want to make all such 273.9 and 274.1 to 274, and wherever there is any number with .1 and .9, it should do the floor and ceil with that so that I always get an integer. 275.5 type numbers are the exception.
I tried to use this :
for i= 2:8351
while data(i,2)~=ceil(data(i,2))
if data(i+1,2)== (data(i,2))+0.1
data(i,2)=floor(data(i,2),0);
elseif data(i-1,2)== (data(i,2))-0.1
data(i,2)=ceil(data(i,2),0);
elseif data(i+1,2)== (data(i,2))-0.1
data(i,2)=ceil(data(i,2),0);
elseif data(i-1,2)== (data(i,2))+0.1
data(i,2)=floor(data(i,2),0);
else
data(i,2)=round(data(i,2),1);
end
end
end
Summary: There are 32 temperatures and around 8000 data points near those 32 temperatures. I want to go to one by one in each column and see if it has .1 or .9 and if so, round(or ceil or floor) it to the nearest integer.
Please help me in programming this.
Thanks.
  댓글 수: 1
Ankit Labh
Ankit Labh 2018년 8월 14일
Question is not specific to 274 but for all temp.

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

채택된 답변

Stephen23
Stephen23 2018년 8월 14일
편집: Stephen23 2018년 8월 14일
This will round values from (X-1).9 to (X).1 to the integer X, otherwise leave the rounded values alone:
>> vec = 1:0.1:2
vec =
1.00 1.10 1.20 1.30 1.40 1.50 1.60 1.70 1.80 1.90 2.00
>> new = round(vec*10)/10;
>> tmp = round(vec*4);
>> idx = mod(tmp,4)==0;
>> new(idx) = tmp(idx)/4
new =
1.00 1.00 1.20 1.30 1.40 1.50 1.60 1.70 1.80 2.00 2.00
  댓글 수: 4
Ankit Labh
Ankit Labh 2018년 8월 17일
This works well !!! Thanks.
Brent F
Brent F 2021년 7월 23일
Clever. @Stephen Cobeldick used a multiplier + round (which rounds in both directions) to leave the middle untouched! I sense a general principle here...

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

추가 답변 (1개)

M
M 2018년 8월 14일
편집: M 2018년 8월 14일
Try this:
temp=[273.9 274.1 274.5];
round(temp*2)/2
ans =
274.0000 274.0000 274.5000
  댓글 수: 1
Ankit Labh
Ankit Labh 2018년 8월 14일
편집: Ankit Labh 2018년 8월 14일
Thank you for your reply. There are 32 temperatures and around 8000 data points near to those 32 temperatures. I want to go to one by one in the column and see if it has .1 or .9 and if so, round(or ceil or floor) it to the nearest integer.

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

카테고리

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