Grouping elements of array according to the result of a calculation ?
Show older comments
Hi Please i would a help with a problem, I am not sure how to approach it: - I have a list of numbers, I want to group them in a groupe, every time the sum of some numbers ( in order ) is divided by 11. It sounds confusing, so let me illustrate it with an exemple :
I have : A, B, C, D, E, F, G, H, I if (A+B)/11 = True then create "array" [A, B] and continue if (A+B+C)/11 = false then continue (A+B+C+D) ect. until i reach the end, then start form if (B+C), (B+C+D) .... ect
i hope that made some sens, please how can i best achieve that ?
Answers (2)
Walter Roberson
on 13 Dec 2017
V = [A, B, C, D, E, F, G, H, I];
outputs = {};
while ~isempty(V)
idx = find( mod(cumsum(V),11) == 0 );
for K = idx
outputs{end+1} = V(1:K);
end
V = V(2:end);
end
1 Comment
mounim korchi
on 13 Dec 2017
Jos (10584)
on 13 Dec 2017
Here is another, straightforward, double for-loop approach (but I do appreciate Walters cumsum solution too):
V = [A B C ... I]
outputs = {} ;
N = numel(V)
for k = 1:N-1
for j = k+1:N
if mod(sum(V(k:j)), 11) == 0
outputs{end+1} = V(k:j) ; % add to set
end
end
end
Categories
Find more on Matrix Indexing 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!