How can I convert this code to C++?
4 views (last 30 days)
Show older comments
data=readtable("240201_100952.csv");
%Delete not intresting data
keep=all(data{:,:}> -90000,2);
filterdata = data(keep,:);
time=filterdata(:,9);
high=filterdata(:,10);
second=time{:,1} ./1000;
high_mm=high{:,1} ./1000;
relativetime=cumsum(second);
%Input motor speed(rpm)
constantspeed=input('Enter the constant speed of the motor:');
pr=0.0128 /2;%Pitch Radius(m)
speed=constantspeed* (2 * pi * pr *1000) / 60;%Unit: mm/s
new_x=relativetime*speed;
%Find polyfit
x = new_x;
y = high_mm;
n = 1;
fit = polyfit(x, y, n);
[p,S,mu]=polyfit(x, y, n);
y_error=polyval(p,x,S,mu);
[y_fit,delta] = polyval(p,x,S,mu);
%Determind the D
t=-( fit(1)*x - y + fit(2)) ./ (fit(1)^2 + 1);
[max_t, idx] = max(t);
[min_t, idy] = min(t);
abs_max_t=abs(max(t));
% 找到对应的点
max_t_x = x(idx);
max_t_y = y(idx);
min_t_x = x(idy);
min_t_y = y(idy);
d=(max_t - min_t)*(sqrt(fit(1)^2 + 1^2));
d_final=d ./2;
%Print
print_Straightness=sprintf('Straightness: %s',d_final);
print_Max=sprintf('Max: %s',abs_max_t);
display(print_Straightness);
display(print_Max);
%Draw figure
figure;
xp=x(1):0.1:x(end);
yp= fit(1)*xp + fit(2);
plot(x,y,'o') ;
hold on
plot(xp,yp,'Color','blue','LineStyle','--');
plot(x,y_fit+2*delta,'m--',x,y_fit-2*delta,'m--')
plot(max_t_x ,max_t_y,'o-','Color','black');
plot(min_t_x ,min_t_y,'o-','Color','red')
hold off
xlabel('Distance(mm)');
ylabel('Different High(mm)');
legend('data','linear fit','Prediction interval')
Answers (1)
Ashutosh Thakur
on 20 Jun 2024
Hi Kun,
The MATLAB code which you have attached can be converted into C++ code by using MATLAB Coder. https://www.mathworks.com/help/coder/index.html.
This example link can assist you in understanding the complete process of code generation using MATLAB Coder: https://www.mathworks.com/help/coder/gs/averaging-filter.html.
But, you must also check that inbuilt MATLAB functions or APIs which are used in the code is supported for code generation or not. Following link can be referred to check for the APIs supported for the code generation: https://www.mathworks.com/help/coder/ug/functions-and-objects-supported-for-cc-code-generation.html.
I hope these resources helps you.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!