Here's the MATLAB code for both Centroid and APIT localization algorithms in WSNs:
1. Centroid Localization:
Matlab
function [estimated_positions] = centroid_localization(positions_anchors, distances_anchors) % This function estimates node positions using the Centroid localization algorithm. % Number of nodes num_nodes = size(distances_anchors, 1); % Estimated positions estimated_positions = zeros(num_nodes, 2); % Loop through each node for i = 1:num_nodes % Get distances to anchor nodes distances = distances_anchors(i, :); % Weight each distance based on inverse square weights = 1 ./ distances.^2; % Calculate weighted centroid estimated_positions(i, :) = sum(weights .* positions_anchors) / sum(weights); end end
Use code with caution. Learn more
content_copy
2. APIT Localization:
Matlab
function [estimated_positions] = apit_localization(positions_anchors, distances_anchors) % This function estimates node positions using the APIT localization algorithm. % Number of nodes num_nodes = size(distances_anchors, 1); % Estimated positions estimated_positions = zeros(num_nodes, 2); % Loop through each node for i = 1:num_nodes % Get distances to anchor nodes distances = distances_anchors(i, :); % Find anchors within communication range in_range_anchors = find(distances > 0 & distances < max(distances)); % Calculate average distance to in-range anchors avg_distance = mean(distances(in_range_anchors)); % Estimated position based on closest anchor closest_anchor = in_range_anchors(distances(in_range_anchors) == min(distances(in_range_anchors))); estimated_positions(i, :) = positions_anchors(closest_anchor, :) + avg_distance * [cos(atan2(positions_anchors(closest_anchor, 2) - estimated_positions(i, 2), positions_anchors(closest_anchor, 1) - estimated_positions(i, 1))), sin(atan2(positions_anchors(closest_anchor, 2) - estimated_positions(i, 2), positions_anchors(closest_anchor, 1) - estimated_positions(i, 1)))]; end end
Use code with caution. Learn more
content_copy
Note:
These are basic implementations and can be improved depending on your specific needs.
You need to define positions_anchors (anchor node positions) and distances_anchors (distances between nodes and anchors) before using these functions.
These algorithms assume range-free localization, meaning they use connectivity information without actual distance measurements.
For better accuracy, consider advanced techniques like incorporating signal strength or time-based measurements.