首页 > 解决方案 > Rounding up to the nearest tenth

问题描述

I am trying to round up the cx_n to its nearest number if the cx_n value doesn't match with yt. With the code below, I can round up but it goes all the way to 1. For example, one of the cx_n values is 0.58, I want to round up 0.6, not 1.0. How can I accomplish this?

This is my MATLAB Code:

Fn = 3; %Nyquist Frequency
Fnr = 6; %Nyquist Rate
Fs = Fnr*5; %Sampling frequency
Ts = 1 / Fs; %Sampling period
T = 1 / 3; 
N = T / Ts; %Number of samples per period
start = 0;
stop =N-1;
c_increment = 1;
c_n = start:c_increment:stop;
c_nTs = c_n*Ts;
cx_n = sin(2*pi*3*c_nTs);
for m_d = 1:length(cx_n)
    for quantisation = 1:length(yt)
        if (m_d ~= quantisation )
            p = round(cx_n);
            stem(c_nTs, p);
        end
        
    end
end

标签: matlabfloating-pointrounding

解决方案


just replace p = round(cx_n); with p = round(cx_n,1);

stem graph

See MATLAB documentation: round

Y = round(X,N) rounds to N digits:

  • N > 0: round to N digits to the right of the decimal point.
  • N = 0: round to the nearest integer.
  • N < 0: round to N digits to the left of the decimal point.

推荐阅读