当前位置: 首页 > news >正文

MATLAB工具箱

一、一维离散数据微分、积分求解

1. 离散积分

function result = integral(x,y,c)result = [];for i=1:1:length(y)c=y(i)*(x(2)-x(1))+c ; result(end+1) = c;end
end

2. 离散微分

function result = differential(x,y)h = x(2)-x(1);result = [];for i=1:1:length(y)if i <= length(y)/2result(end+1) = (y(i+1)-y(i))/h;elseresult(end+1) = (y(i)-y(i-1))/h;endend
end

3. 测试代码

x = 0:0.001:2;
y = x;
y1 = integral(x,y,1);
plot(x,y);hold on
plot(x,y1);
figure;
y2 = differential(x,y1)
plot(x,y1);hold on
plot(x,y2)

Reference

  1. matlab离散数据微积分

二、空间几何计算

1. 计算点到直线的距离

function d = distanceToLine3D(P, P1, P2)% P: 点 [x0, y0, z0]% P1: 直线上的点1 [x1, y1, z1]% P2: 直线上的点2 [x2, y2, z2]% 计算向量 v 和 dv = [P(1) - P1(1), P(2) - P1(2), P(3) - P1(3)];d = [P2(1) - P1(1), P2(2) - P1(2), P2(3) - P1(3)];% 计算投影长度 p 的分子部分numerator = dot(v, d);denominator = norm(d)^2;% 计算投影长度 p 的绝对值(如果需要非负值)p = max(0, min(numerator / denominator, 1)) * norm(d); % 限制在 [0, 1] 内% 计算距离 d(P, L)d = norm(v) - p;
end