clustering the random numbers

10 views (last 30 days)
Lakshmi Thara R
Lakshmi Thara R on 17 Jun 2021
Answered: Arjun on 4 Feb 2025
Hi, Im having 10 number of ones and 30 zeros places in the random position in 1x40 matrix. now i need to cluster 1's side by side (adjacent 1's) among 10 1's.The max number of adjacent ones is nmax? So if nmax is 5, then maximum number of adjacent ones will be 5.Thank You

Answers (1)

Arjun
Arjun on 4 Feb 2025
According to my interpretation of the question, I understand that you have a 1x40 matrix and an argument 'nmax'. The input matrix is such that it contains 10 ones and remaining 30 zeros and the requirement is such that you want to place ones adjacent to one another but no more than 'nmax' number of ones can be adjacent.
Since the total count of ones and zeros is fixed, you can write your algorithm as follows:
  1. Initialize a matrix 'M' which is 1x40 with all zeros, a variable 'remaining_to_place' with 10 which is the count of ones still to be placed in the matrix, a variable 'nmax' to 5 or any other desired value, a variable 'position' to 1 which will contain the location where we have to place a one and a variable 'count' to 0 which will keep track of how many adjacent ones are placed.
  2. Start a 'while' loop with the condition that 'remaining_to_place > 0'.
  3. In the body of the while loop place a 'if' check whether 'count < nmax'. If true then increment count by 1, place a one in the matrix at location pointed by position i.e 'M(position)=1', increment position by 1 and decrement 'remaining_to_place' by 1.
  4. If the result of 'if' was false then in the else part increment 'position' by 1 to break placing more than 'nmax' ones together, set 'count' back to 0.
Kindly refer to the code below for the implementaion of the above algorithm:
function M = createMatrix(nmax)
% Initialize the matrix and variables
M = zeros(1, 40);
remaining_to_place = 10;
position = 1;
count = 0;
% Place ones in the matrix
while remaining_to_place > 0
if count < nmax
count = count + 1;
M(position) = 1;
position = position + 1;
remaining_to_place = remaining_to_place - 1;
else
position = position + 1;
count = 0;
end
end
end
nmax = 5; % It must be greater than 0
resultMatrix = createMatrix(nmax);
disp(resultMatrix);
Kindly refer to the documenation of 'while' loop here: https://www.mathworks.com/help/releases/R2021a/matlab/ref/while.html
I hope this helps!

Categories

Find more on Get Started with MATLAB 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!