Clear Filters
Clear Filters

Seperating vectors when reaching a threshold value

3 views (last 30 days)
What I am trying to do is seperate a vector into other vectors when the second column of the sums to a certain values and then repeat again once it reaches a another value; so it produces seperate vectors.
For example
A(1)=[1; 3; 4; 6; 1; 2; 4; 3; 5; 2; 1; 4; 2; 4]
A(2)=[3; 5; 7; 4; 9; 1; 5; 6; 8; 9; 6; 2; 4; 1]
So when A(2) summation reaches 20, it will produce a new vector B
B(1)=[1; 3; 4; 6]
B(2)=[3; 5; 7; 4]
So when A(2) summation reaches 50 it will produce a new vector C
C(1)=[1; 2; 4; 3; 5]
C(2)=[9; 1; 5; 6; 8]
and so on.
Any help would be much appreciated
  1 Comment
Azzi Abdelmalek
Azzi Abdelmalek on 12 Jun 2013
Edited: Azzi Abdelmalek on 12 Jun 2013
What is A(2) summation? and What A(1) is doing in your question? and what after 20, then 50?

Sign in to comment.

Answers (2)

David Sanchez
David Sanchez on 12 Jun 2013
You do not have many clues of what is going on in your code, but this could be of some help and give you some ideas about what to do next:
A_1=[1; 3; 4; 6; 1; 2; 4; 3; 5; 2; 1; 4; 2; 4];
A_2=[3; 5; 7; 4; 9; 1; 5; 6; 8; 9; 6; 2; 4; 1];
sum = 0;
my_limit = 20;
for k=1:length(A_2)
sum = sum + A_2(k);
if sum > my_limit
B_1 = A_1(1:k-1);
B_2 = A_2(1:k-1);
break; % get out of for-loop
end
end
my_limit = 50;
for k2 = k:length(A_2)
sum = sum + A_2(k2);
if sum > my_limit
C_1 = A_1(k:k2-1);
C_2 = A_2(k:k2-1);
break; % get out of for-loop
end
end

Azzi Abdelmalek
Azzi Abdelmalek on 12 Jun 2013
A{1}=[1; 3; 4; 6; 1; 2; 4; 3; 5; 2; 1; 4; 2; 4];
A{2}=[3; 5; 7; 4; 9; 1; 5; 6; 8; 9; 6; 2; 4; 1];
a=cumsum(A{2});
m=max(a);
a(end)=a(end)+1;
id=unique([20 50:50:m m]);
idx2=arrayfun(@(x) find(a>x,1),id);
idx2=[idx2(1:end-1)-1 idx2(end)];
idx1=[1 idx2(1:end-1)+1];
for k=1:numel(idx1);
out{k,1}=A{1}(idx1(k):idx2(k))';
out{k,2}=A{2}(idx1(k):idx2(k))';
end
% Check the result
%first arrays
B1=out{1,1}
C1=out{1,2}
%second arrays
B2=out{2,1}
C2=out{2,2}
%third array
B3=out{3,1}
C3=out{3,2}

Categories

Find more on Creating and Concatenating Matrices 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!