how to extract n elements from a vector and store them in a matrix
Show older comments
Hi,
I have a matrix with 3 variables:
a = [3 6 0 3 8 4 9 1 2 4 9 3 2 5 7 0 1 2.....]
b = [5 6 5 3 1 3 8 2 2 3 5 7 1 2 6 1 6 7.....]
c = [0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0.......]
I want to write a for loop that every time that c == 1 goes to the corresponding position of a and b, cuts 5 elements from each vector and stores them in two different matrices that would look something like this:
matrix a
a1 8 4 9 1 2
a2 2 5 7 0 1
a3 ....
matrix b
b1 1 3 8 2 2
b2 1 2 6 1 6
b3 .....
any idea on how to do it?
Accepted Answer
More Answers (2)
a = [3 6 0 3 8 4 9 1 2 4 9 3 2 5 7 0 1 2];
b = [5 6 5 3 1 3 8 2 2 3 5 7 1 2 6 1 6 7];
c = [0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0];
in1=find(c);
in2=in1'+[0:4];
NewA=a(in2)
NewB=b(in2)
1 Comment
Hernia Baby
on 20 Jun 2022
This solution is amazing! I like it!
Hernia Baby
on 20 Jun 2022
Edited: Hernia Baby
on 20 Jun 2022
a = [3 6 0 3 8 4 9 1 2 4 9 3 2 5 7 0 1 2];
b = [5 6 5 3 1 3 8 2 2 3 5 7 1 2 6 1 6 7];
c = [0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0];
temp = cumsum(c)
for ii = 1:max(temp)
ta = a;
tb = b;
ta(temp~=ii)=[];
tb(temp~=ii)=[];
A{ii,1}=ta(1:5);
B{ii,1}=tb(1:5);
end
A=cell2mat(A)
B=cell2mat(B)
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!