how to extract n elements from a vector and store them in a matrix
42 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sarah Boukarras
el 20 de Jun. de 2022
Comentada: Hernia Baby
el 20 de Jun. de 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 comentarios
Respuesta aceptada
Image Analyst
el 20 de Jun. de 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 comentarios
Más respuestas (2)
Fangjun Jiang
el 20 de Jun. de 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 comentario
Hernia Baby
el 20 de Jun. de 2022
Editada: Hernia Baby
el 20 de Jun. de 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 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!