creating spatial heat map in matlab for one variable with x,y coordinates

13 views (last 30 days)

I am new to matlab. I have huge list of x, y coordinates of an object moving. I want calculate velocity with coordinates and check velocity change in whole arena.
Question A : I used diff of X (i) and Y(j) in this formula - distance = sqrt(i^2 + j^2) then used 'gdivide (distance,time)' to calculate velocity. But my for loop is not working properly , its not calculating distance with correspoding x and y coordinates. When I try process whole data, I got below shown error, what is good practice to tackle that?
[Error using bsxfun - Requested 112899x112898 (95.0GB) array exceeds maximum array size preference (16.0GB). This might cause MATLAB to become unresponsive.]
Question B : I want to plot the velocity as gradient on arena (pixel aspect ratio) map, like spatial heatmap on representation of actual arena. I want especialy focused to see the velocity dropping regions in arena, which plot will be suitable?

  2 Comments
Mathieu NOE
Mathieu NOE on 5 Nov 2024
hello
can you share a small portion of your data ? and code if you have one ?
Supraja
Supraja on 5 Nov 2024
my data is like this : x coords - 117.415351867676
117.722839355469
118.030349731445
118.337844848633
118.645355224609
118.952865600586
119.260368347168
119.567871093750
119.875373840332
y coords - 2.01796388626099
2.38077235221863
2.74358034133911
3.10638880729675
3.46919679641724
3.83200550079346
4.19481325149536
4.55762195587158
4.92043018341064

Sign in to comment.

Answers (2)

Umar
Umar on 6 Nov 2024

Hi @Supraja,

After going through your comments, the key steps involve calculating the distance between consecutive points, determining the time intervals, and then computing the velocity. Additionally, you need to visualize the velocity as a spatial heatmap to identify regions of velocity drop. I will suggest the following step by step approach that will help you accomplish your task. Use the Euclidean distance formula to compute the distance between consecutive points. If the time intervals are uniform, you can use a constant time value; otherwise, you will need to provide the time data. Velocity will be calculated as distance divided by time. Finally, use a heatmap to represent the velocity across the arena. Here is a complete MATLAB code that implements the above steps:

% Sample Data
x_coords = [117.415351867676, 117.722839355469, 118.030349731445, ...
          118.337844848633, 118.645355224609, 118.952865600586, ...
          119.260368347168, 119.567871093750, 119.875373840332];
y_coords = [2.01796388626099, 2.38077235221863, 2.74358034133911, ...
          3.10638880729675, 3.46919679641724, 3.83200550079346, ...
          4.19481325149536, 4.55762195587158, 4.92043018341064];
% Assuming uniform time intervals (e.g., 1 second)
time_interval = 1; % seconds
% Number of points
num_points = length(x_coords);
% Preallocate distance and velocity arrays
distances = zeros(num_points - 1, 1);
velocities = zeros(num_points - 1, 1);
% Calculate distances and velocities
for i = 1:num_points - 1
  % Calculate distance using Euclidean formula
  distances(i) = sqrt((x_coords(i+1) - x_coords(i))^2 + ...
                      (y_coords(i+1) - y_coords(i))^2);
    % Calculate velocity
    velocities(i) = distances(i) / time_interval;
  end
% Display the calculated velocities
disp('Calculated Velocities:');
disp(velocities);
% Create a heatmap of velocities
figure;
scatter(x_coords(1:end-1), y_coords(1:end-1), 100, velocities, 'filled');
colorbar;
title('Velocity Heatmap');
xlabel('X Coordinates');
ylabel('Y Coordinates');
axis equal;
grid on;

Please see attached.

My suggestions for best practices for future code development

Vectorization: Instead of using a for loop, consider vectorized operations for better performance, especially with large datasets. MATLAB is optimized for matrix operations.

Memory Management: Ensure that your data does not exceed MATLAB's memory limits. If you encounter memory issues, consider processing the data in smaller chunks.

Error Handling: Implement error handling to manage unexpected inputs or conditions gracefully.

By following the outlined steps and utilizing the provided code, you should be able to effectively analyze the velocity changes across the arena and identify regions of interest.

If you have further questions or need additional assistance, feel free to ask!

  2 Comments
Supraja
Supraja on 6 Nov 2024
Thanks @Umar!, I am able to calculate velocity. While plotting I'm getting this error - (Error using scatter (line 68) Color must be one RGB triplet, an m-by-3 matrix of RGB triplets with one color per scatter point, or an m-by-1 vector with one value per scatter point.) So, I'm trying to create colormap for velocities.
Umar
Umar on 6 Nov 2024 at 14:41

Hi @Supraja,

The root cause of this error typically arises when the color data provided to the scatter function does not conform to the required specifications. Specifically, the color input must either be:

  • A single RGB triplet (e.g., [1, 0, 0] for red).
  • An m-by-3 matrix where each row corresponds to an RGB triplet for each point.
  • An m-by-1 vector that specifies a single color value for each point, which is then mapped to a colormap.

If the color data is incorrectly formatted or if the dimensions do not match the number of data points, this error will occur. To resolve this issue, you need to ensure that the color data is correctly formatted. Below is a snippet code that includes the creation of a colormap based on the velocity values.

% Sample data for demonstration
x = 1:10; % X data points
y = rand(1, 10) * 10; % Y data points (random values)
velocity = rand(1, 10) * 100; % Velocity values (random values)
% Normalize the velocity for colormap
normalized_velocity = (velocity - min(velocity)) / (max(velocity) - 
min(velocity));
% Create a colormap
cmap = parula(256); % Using the 'parula' colormap
color_indices = round(normalized_velocity * (size(cmap, 1) - 1)) + 1; 
% Map   velocities to colormap indices
colors = cmap(color_indices, :); % Get the corresponding RGB colors
% Create scatter plot
figure;
scatter(x, y, 100, colors, 'filled'); % Use the colors for the scatter points
colorbar; % Optional: Add a colorbar to indicate velocity
title('Velocity Scatter Plot');
xlabel('X-axis');
ylabel('Y-axis');

Please see attached.

In this code, normalize the velocity values to fit within the range of the colormap, created a colormap using the parula function, which is a perceptually uniform colormap and then map the normalized velocity values to the indices of the colormap and retrieve the corresponding RGB colors. Finally, use these colors in the scatter function.

I would suggest to review @Walter Roberson’s comments. He has years of experience and always provide better advice to resolve problems.

Sign in to comment.


Walter Roberson
Walter Roberson on 6 Nov 2024
You tried to calculate the pairwise distance between 112899 points . The way your code is structured, that involves building a 112899 by 112899 array, with 8 bytes per entry (because double precision). Such an array would require about 95 gigabytes, but your system is configured for a maximum of 16 gigabytes.
You can configure Preferences to not restrict array sizes. That would permit your system to use swap space to calculate the array. Swap space is pretty slow but at least it would eventually get the job done. Several days or a week or two roughly.
Or you can reconfigure the code so that it loops calculating the distance between one specific point and all the other points, and does something to summarize the resulting distances, and then continues on with the loop. With a bit of work, you could use this kind of loop to find the second-closest distance between points (the closest distance is each point to itself, which is a distance of zero.)
Or you can use something like a KDTreeSearcher together with knnsearch to find the second closest point to each point in an efficient way

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Products


Release

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!