how to extract n elements from a vector and store them in a matrix
36 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Sarah Boukarras
am 20 Jun. 2022
Kommentiert: Hernia Baby
am 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 Kommentare
Akzeptierte Antwort
Image Analyst
am 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 Kommentare
Weitere Antworten (2)
Fangjun Jiang
am 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)
1 Kommentar
Hernia Baby
am 20 Jun. 2022
Bearbeitet: Hernia Baby
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!