how to extract n elements from a vector and store them in a matrix

23 views (last 30 days)
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

Image Analyst
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.
aMatrix = 2×5
8 4 9 1 2 2 5 7 0 1
bMatrix % Show in command window.
bMatrix = 2×5
1 3 8 2 2 1 2 6 1 6
and this:

More Answers (2)

Fangjun Jiang
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)
NewA = 2×5
8 4 9 1 2 2 5 7 0 1
NewB=b(in2)
NewB = 2×5
1 3 8 2 2 1 2 6 1 6

Hernia Baby
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)
temp = 1×18
0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2
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)
A = 2×5
8 4 9 1 2 2 5 7 0 1
B=cell2mat(B)
B = 2×5
1 3 8 2 2 1 2 6 1 6

Categories

Find more on Get Started with MATLAB 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!