while循环中如何对比当前步与上一步计算得到的sigdB值
相邻迭代步
sigdB值对比实现方法 核心逻辑是单独定义变量存储上一轮迭代的计算结果,每轮计算完当前值后先做对比,再将当前值存入该变量供下一轮使用,首次迭代无历史数据时做空值判断避免报错。
修改步骤
- 在
while循环外部提前初始化存储上一步值的变量,用NaN标记无历史数据的初始状态 - 循环内计算得到当前步
sigdB后,判断存在上一步历史值时,执行需要的对比逻辑(差值计算、大小判断、结果打印/可视化都可以在这个环节添加) - 每轮迭代的点位更新、绘图刷新逻辑跑完后,将当前
sigdB赋值给存储历史值的变量,作为下一轮的对比基准
修改后可直接运行的完整代码
注:已修正原代码里XY2初始Y坐标误用参数g的笔误,运行前需要给代码中用到的power变量赋实际物理值
npts=1;center=[0 0];radius=1000; npts2=1;center2=[0 0];radius2=1000; velocity = 45/3.6; velocity2 = 45/3.6; theta = rand(npts, 1) * 2*pi; g = 0.5 * radius + 0.5 * radius * rand(npts,1); X_x=center(1)+g.*cos(theta); Y_y=center(2)+g.*sin(theta); XY = [X_x ,Y_y]; theta2 = rand(npts2, 1) * 2*pi; g2 = 0.5 * radius2 + 0.5 * radius2 * rand(npts2,1); % 修正原代码笔误:Y_y2计算使用g2而非g X_x2=center2(1)+g2.*cos(theta2); Y_y2=center2(2)+g2.*sin(theta2); XY2 = [X_x2 ,Y_y2]; hfig = figure('Color', 'w'); hax = axes('Parent', hfig); hdots(1) = plot(XY(1,1),XY(1,2),'Parent', hax,'Marker', '.','Color', 'k','LineStyle', 'none','MarkerSize', 10); hold(hax, 'on'); axis(hax, 'equal'); hdots(2) = plot(XY2(1,1),XY2(1,2),'Parent', hax,'Marker', '.','Color', 'r','LineStyle', 'none','MarkerSize', 10); hold(hax, 'on'); axis(hax, 'equal'); % 绘制点位活动范围圆 t = linspace(0, 2*pi, 100); plot(radius * cos(t) + center(1),radius * sin(t) + center(2)) % 初始化上一步sigdB存储变量,初始状态设为NaN prev_sigdB = NaN; while all(ishghandle(hdots)) distPoints = pdist2(XY,XY2,'euclidean'); sig=sum(power*(distPoints).^-2); % 运行前需提前给power变量赋值 sigdB=10*log(sig); % 相邻步sigdB对比逻辑,可根据实际需求修改 if ~isnan(prev_sigdB) delta = sigdB - prev_sigdB; % 示例:命令行打印当前值和每秒变化量 fprintf('当前信号强度:%.2f dB,较上一秒变化:%.2f dB\n',sigdB,delta); end direction2 = rand(npts, 1) * 2 *pi; direction = rand(npts, 1) * 2 *pi; [XY2, direction2] = step(XY2, direction2, velocity2, radius2, center2); [XY, direction] = step(XY, direction, velocity, radius, center); set(hdots(2), 'XData', XY2(1,1), 'YData', XY2(1,2)); set(hdots(1), 'XData', XY(1,1), 'YData', XY(1,2)); drawnow; % 更新存储变量,把当前sigdB设为下一轮的"上一步值" prev_sigdB = sigdB; pause(1); end
内容的提问来源于stack exchange,提问作者omar aljubory
相关产品推荐
相关产品推荐

