Clear Filters
Clear Filters

is there a way to make matrices out of a bigger matrix with a changing condition without using a loop

1 view (last 30 days)
so i have the points of a field in a 2D matrix and a line is cutting that field , i want to take only points which are below the field . is there a way for me to put some condition when i make another matrix from the field such that i only consider the points below that field without using any loop ?
using a loop will make my code very heavy and hence i want to avoid that .

Answers (1)

Rohit Kulkarni
Rohit Kulkarni on 8 Sep 2023
Hi Kashish,
I understand that you have a matrix and a line cut through it, and you would like to obtain the points which are below the line without using a for loop.
The points below the line can be filtered by using logical indexing and matrix operations.
The general approach is:
  • Define line equation.
  • Create logical mask and use it to identify points below the line equation.
The following code snippet shows an example of this:
% Define the parameters of the line equation: y = mx + b.
m = 0.5; % Slope of the line
b = 10; % Y-intercept of the line
% Create a 2D matrix representing your field (random data in this case).
% Replace this with your actual data.
fieldSize = 100;
fieldMatrix = rand(fieldSize, fieldSize) * 100;
% Create an array of x-coordinates corresponding to the columns of the matrix.
xCoordinates = 1:fieldSize;
% Create a matrix of y-coordinates based on the line equation.
yCoordinates = m * xCoordinates + b;
% Create a logical mask to identify points below the line.
mask = (1:fieldSize)' > yCoordinates;
% Extract the points below the field using the logical mask.
pointsBelowField = fieldMatrix;
pointsBelowField(mask) = NaN; % Set points above the line to NaN
% Create a matrix of values for the points above the line.
pointsAboveField = fieldMatrix;
pointsAboveField(~mask) = NaN; % Set points below the line to NaN
% Display both matrices
figure;
% Display the points below the line
subplot(1, 2, 1);
imagesc(pointsBelowField);
colormap('jet');
title('Points Below Line');
colorbar;
% Display the points above the line
subplot(1, 2, 2);
imagesc(pointsAboveField);
colormap('jet');
title('Points Above Line');
colorbar;
% Display both plots side by side
sgtitle('Points Above and Below Line');
Hope it resolves your query!

Categories

Find more on Colormaps in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!