举个例子应该没问题。
- 随机生成器停止一次生成一次的固定点。
-
cDistance 函数返回初始固定点和随机点之间的距离(作为列标题)
- 如果我们将
re_point 设置为 1,则能够重新创建固定点
我将您的代码封装成一个函数,因此我们可以利用定义一个persistent 变量。这种类型的变量保留在内存中。你的情况下的两个变量是xtemp和ytemp(还有图形句柄hFig,所以我们不必创建新的图形窗口)
function TESTING (re_point)
persistent xtemp ytemp hFig
变量re_point 是一个可以定义为0 或1 的变量。如果没有参数运行,则默认变量是从此代码中定义的。 nargin 是函数传入的参数个数
if nargin<1
re_point = 0;
end
如果您的固定值x_temp 和y_temp 的persistent 变量已经设置,我们不需要设置这些值。此外,如果我们调用了函数TESTING(1),这会将值re_point 设置为1,因此满足以下if 语句,然后生成新的不动点
if (isempty(xtemp) && isempty(xtemp)) || re_point == 1
% Generate x and y position of tags
xtemp = A1*rand(1,N);
ytemp = A1*rand(1,N);
end
为了标注随机点,我使用text函数将每个随机点的值如下放置。
for iter = 1:numel(xtemp_2)
text(xtemp_2(iter),ytemp_2(iter), num2str(iter),...
'FontSize',8,'HorizontalAlignment','center',...
'Color','White','FontWeight','bold');
end
有很多方法可以对距离的计算进行编码。我会让你找到更优雅的方法。我使用了一个嵌套函数来做到这一点。在大多数情况下(如果不是所有情况),嵌套函数都受益于速度。缺点是任何嵌套函数都是父函数的本地函数。我简单地遍历了每个固定点和随机点,并使用了内置的pdist MATLAB 函数如下
function S = distanceCalc
S = size(numel(xtemp),numel(xtemp_2));
for ri = 1:numel(xtemp)
for fi = 1:numel(xtemp_2)
S(ri,fi) = pdist([xtemp(ri),ytemp(ri);...
xtemp_2(fi),ytemp_2(fi)],...
'euclidean');
end
end
end
这是完整的代码
function TESTING (re_point)
% if re_point = 0 [default]
% points generated for xtemp and y_temp remain fixed
% if re_point = 1
% new points are generated for x_temp and y_temp
persistent xtemp ytemp hFig
if nargin<1
re_point = 0;
end
A1 = 30; % area defined as 30 X 30 grid
N = 10;
R = 3; % 3 readers
s = rng; % fixed tags does not change position when simulated repatedly
rng(s)
if (isempty(xtemp) && isempty(xtemp)) || re_point == 1
% Generate x and y position of tags
xtemp = A1*rand(1,N);
ytemp = A1*rand(1,N);
end
if isempty(hFig)
hFig = figure;
end
% Generate x and y position of points
xtemp_2 = A1*rand(1,R);
ytemp_2 = A1*rand(1,R);
% plot data
plot(xtemp,ytemp,'.',xtemp_2,ytemp_2,'rs','LineWidth',1,'MarkerEdgeColor','k','MarkerFaceColor','r','MarkerSize',14);
for iter = 1:numel(xtemp_2)
text(xtemp_2(iter),ytemp_2(iter), num2str(iter),...
'FontSize',8,'HorizontalAlignment','center',...
'Color','White','FontWeight','bold');
end
grid on
% hold off
axis([0 A1 0 A1])
% Tag formatting
xoffset = 0;
yoffset = -1;
fsize = 8;
temp_str = mat2cell(num2str([xtemp(:) ytemp(:)], '(%.2f,%.2f)'), ones(1,N));
text(xtemp+xoffset, ytemp+yoffset, temp_str,'fontsize', fsize)
cDistance = distanceCalc()
% distance function calculator
function S = distanceCalc
S = size(numel(xtemp),numel(xtemp_2));
for ri = 1:numel(xtemp)
for fi = 1:numel(xtemp_2)
S(ri,fi) = pdist([xtemp(ri),ytemp(ri);...
xtemp_2(fi),ytemp_2(fi)],...
'euclidean');
end
end
end
end