⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 demo_float2fixed.m

📁 Accelerating execution speed of fixed-point algorithms in MATLAB and Simulink
💻 M
字号:
%% Let's start by composing a simple flaoting point
% algorithm caled hz_average0.m which finds the scalar 
% average value of a matrix
x=[1:5;6:10]
acc=0
y=hz_average0(x,acc)

%% Convert to fixed-point data types in M 
% modify the algorithm to fixed-point: adding line(s) to M-code
% call the new fixed-point m-code hz_average1.m
% and run with default fixed-point settings;
% Observe scaling issues! the average value should be 5.5 
% yet it comes out incorrectly as 0.1!
x_fix=fi(x);
x_fix.data
acc_fix=fi(0);
acc_fix.data
[y_fix,acc_fix]=hz_average1(x_fix,acc_fix);
y_fix.data

%% Notice scaling problem: problem is with the accumulator:
% acc_fix variable. What's its dynamic range?
% How to best share the accumulator total bits 
% into integer and fractional bits?
% The answer: use Fixed-Point Toolbox features
% data logging and data type override 
% to log the full numerical range of variables 
% to ultimately find out the best sharing scheme for bits
fipref('LoggingMode','on');
fipref('DataTypeOverride','ScaledDoubles');
x_fix=fi(x);
acc_fix=fi(0);
[y_fix,acc_fix]=hz_average1(x_fix,acc_fix);
fipref('LoggingMode','off');
reset(fipref);
A=logreport(x_fix,acc_fix,y_fix);
%% What is the structure of A (logreport) like? 
% In Scaled Double Data type override mode:
% variable A here, logs minimums, maximums, overflows and underflows
% based on real-world values that went through the fi objects 
% in function call to hz_average1.m 
A
%% What is content description for variable A?
A.name
%% Get access to its recording of minimum and maximum 
% values as shown in the table using dot notation inquiry
[A.minlog ;A.maxlog]'
%% Now second varibale acc_fix corresponds to 2nd elements of
% logreport variable A, which is the accumulator 
[A(2).minlog A(2).maxlog]
%% Let's fix scaling of this variable based on an easy 
% formula relating dynamic range to integer bit allocation
% to avoid overflows: 
% Compute the integer part to fit variable within range
% Compute the fraction length as the rest of bit budget
R = max([abs(A(2).minlog),abs(A(2).maxlog)]);
signed =1;
wordlength = 16;
integer_part = ceil(log2(R));
fractional_part=  wordlength - integer_part - signed;
%% Construct the fixed-point numeric type object
% which avoids overflows
T=numerictype(signed,wordlength,fractional_part)
%% Proper scaling is done by this intelligent
% allocation of bits, as a result of this range analysis
% Now run fixed-point hz_average1.m again and 
% observe you get the right value
acc_fix=fi(acc,T);
[y_fix,acc_fix]=hz_average1(x_fix,acc_fix);
%% Verify that in fixed-point you get the right accumulator
% value of 55 and right average of 5.5
test=[acc_fix.data y_fix.data]

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -