MATLAB Matlab code natural numbers subset

AI Thread Summary
The discussion focuses on a mathematical problem involving an array of natural numbers from 1 to n, divided into m groups, where m*(m-1)=n. The goal is to extract specific elements from each group: all m-1 elements from the first group, the last m-2 elements from the second group, the last m-3 elements from the third group, and so on, down to zero elements from the last group. An example is provided with m=5, resulting in groups of four elements each. A brute force solution is shared, utilizing cell arrays to accommodate the varying sizes of the output. The provided code snippet demonstrates how to create the groups and extract the required elements, showcasing a straightforward yet functional approach to the problem.
martika
Messages
2
Reaction score
0
I have array of natural numbers from 1 to n.
They are divided into m groups, where m*(m-1)=n.
I need all m-1 elements from first group, last m-2 elements from second group, last m-3 elements from third group...zero elements from last group.
For example
5*4=20:
1,2,3,4; 5,6,7,8; 9,10,11,12; 13,14,15,16; 17,18,19,20;.
I need 1,2,3,4; 6,7,8; 11,12; 16;
Thanks!
 
Physics news on Phys.org
Here is a brute force, inelegant, solution to your problem using cell arrays to hold to the final values since they are not equal in size. Do with it as you will :p

Code:
m = 5;
n = m*(m-1);
numbers = 1:n;

for i = 1:m
    
    j = i-1;
    
    group(i,:) = numbers((m-1)*j+1:(m-1)*i);
    
    group_ends{i} = group(i,i:end);
    
end
 
Thank you!
 

Similar threads

Back
Top