MATLAB Answers

I need to make groups from array

1 view (last 30 days)
zhoug zho
zhoug zho on 30 Jun 2021
Edited: zhoug zho on 1 Jul 2021
I have this array, I need to make groups of these 14 elements with the rule that if value of a new element is 1 to 5 percent higher than the value of previous elements then the new element will be part of previous group, otherwise new group will start if it is higher than 5%. Thanks
  5 Comments
zhoug zho
zhoug zho on 30 Jun 2021
can you give an example based on our discussion, . then i will try to adjust the loop according to my need.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 30 Jun 2021
A = [.06, .18, .15, .14, .13, .12, .125, .15, .105, .115, .34, .32, .03 .14]
A = 1×14
0.0600 0.1800 0.1500 0.1400 0.1300 0.1200 0.1250 0.1500 0.1050 0.1150 0.3400 0.3200 0.0300 0.1400
mask = A(2:end) > 1.05 * A(1:end-1);
group_lengths = diff([0, find(mask), length(A)])
group_lengths = 1×6
1 6 2 1 3 1
mat2cell(A, 1, group_lengths)
ans = 1×6 cell array
{[0.0600]} {[0.1800 0.1500 0.1400 0.1300 0.1200 0.1250]} {[0.1500 0.1050]} {[0.1150]} {[0.3400 0.3200 0.0300]} {[0.1400]}
  6 Comments
zhoug zho
zhoug zho on 1 Jul 2021
got it... Thank you so much.

Sign in to comment.

More Answers (1)

David Hill
David Hill on 30 Jun 2021
Some guessing. You only said it stays in group is greater by 1-5%, I assumed a new group otherwise. Anyways, you modify the below to meet your needs.
n{1}=yourArray(1);
c=1;
for k=2:length(yourArray)
if yourArray(k)<=1.05*yourArray(k-1)&&yourArray(k)>=1.01*yourArray(k-1)
n{c}=[n{c},yourArray(k)];
else
c=c+1;
n{c}=yourArray(k);
end
end
  2 Comments
Walter Roberson
Walter Roberson on 30 Jun 2021
However, if it is lower it needs to stay with the group being built according to https://www.mathworks.com/matlabcentral/answers/868868-i-need-to-make-groups-from-array#comment_1613113 and that means that you should not be testing against a lower bound. The 1% is a red herring; the only question is more than 5% increase (new group) otherwise continue the same group.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!