Append to vector of different sizes in for loop
Mostrar comentarios más antiguos
Hi.
How does one append a vector to a another vector within a loop.
I have the code below: Point is i want the signal between the first and second indices of ipts. then the third and fourth et cetera up to the nineteenth to twentieth.
with this code I only get the last part nineteenth to twentieth.
i = 1;
while i < 19;
A = TimeSeries_short(ipts(i):ipts(i+1));
i = i+2;
end
.mat file is attached.
Respuesta aceptada
Más respuestas (1)
dpb
el 14 de Feb. de 2021
The short answer is
i = 1;
A=[];
for i=1:2:numel(ipts)
A = [A;TimeSeries_short(ipts(i):ipts(i+1),:);
end
Normally one frowns on dynamic reallocation, but presuming the overall array is going to be relatively small, the time taken won't be excessive.
If A is going to be very large, then one will want to calculate the final size and compute the indices going in and explicitly set the rows.
6 comentarios
Jørgen Fone Pedersen
el 14 de Feb. de 2021
Jørgen Fone Pedersen
el 14 de Feb. de 2021
dpb
el 14 de Feb. de 2021
Need rest of the error message in context to be able to identify which array it didn't like..
What does
whos ipts TimeSeries_short
return?
Jørgen Fone Pedersen
el 15 de Feb. de 2021
OK, I presumed a column-wise array, not a vector.
Hence I referenced
T(i1:i2,:)
to pull all rows of the array T, not just a single column. For a vector need just the 1D indexing expression.
A = [A;TimeSeries_short(ipts(i):ipts(i+1))];
instead for a vector (column output); replace semi-colon with comma for row output.
Jørgen Fone Pedersen
el 15 de Feb. de 2021
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!