how to extract n elements from a vector and store them in a matrix
16 views (last 30 days)
Show older comments
Sarah Boukarras
on 20 Jun 2022
Commented: Hernia Baby
on 20 Jun 2022
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?
0 Comments
Accepted Answer
Image Analyst
on 20 Jun 2022
Try this:
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];
locations1 = find(c == 1);
aMatrix = zeros(numel(locations1), 5);
bMatrix = zeros(numel(locations1), 5);
for row = 1 : numel(locations1)
thisIndex = locations1(row);
aMatrix(row, :) = a(thisIndex : thisIndex + 4);
bMatrix(row, :) = b(thisIndex : thisIndex + 4);
end
aMatrix % Show in command window.
bMatrix % Show in command window.
and this:
0 Comments
More Answers (2)
Fangjun Jiang
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];
in1=find(c);
in2=in1'+[0:4];
NewA=a(in2)
NewB=b(in2)
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)
0 Comments
See Also
Categories
Find more on Logical 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!