How can I vectorize this for loop?

1 visualización (últimos 30 días)
Matthew Casiano
Matthew Casiano el 9 de Sept. de 2021
Editada: Matthew Casiano el 10 de Sept. de 2021
I am having a hard time vectorizing this for loop. In this example I am trying to fill a matrix from a data vector (it is numbered 1 through 96 for testing out the script, but would eventually contain real data). Each matrix column covers a different range of indices from the data vector. Thanks,
% These are example values for testing script. They can change, but
% are tied together so do not change values or datamatrix will not be resolved
BS=16; % this value is specific to the size of the DataVector; just listed here for this example, do not change or matrix will not resolve
ptsOL=8; % this value is specific to the size of the DataVector; just listed here for this example, do not change or matrix will not resolve
NoBlocks=11; % this value is specific to the size of the DataVector; just listed here for this example, do not change or matrix will not resolve
DataVector=1:96; % Data - numbered 1 through 96 for testing out the script, but would eventually contain real data, do not change or matrix will not resolve
%%%% How to vectorize the following for loop
DataMatrix=zeros(BS,NoBlocks); % initialize matrix
for i=1:NoBlocks
DataMatrix(:,i)=DataVector((i-1)*(BS-ptsOL)+1:(i-1)*(BS-ptsOL)+BS); % place all data blocks into separate consecutive columns
end

Respuesta aceptada

TADA
TADA el 9 de Sept. de 2021
irow = (0:(NoBlocks-1))*ptsOL+1;
icol = (0:BS-1)';
idxMat = irow+icol;
DataMatrix = DataVector(idxMat);
  1 comentario
Matthew Casiano
Matthew Casiano el 9 de Sept. de 2021
Editada: Matthew Casiano el 10 de Sept. de 2021
This is great! Thanks for your help.
I've never seen this convention in creating vectors with spaced increments either. Makes sense to use parentheses since they take precedence and the range is evaluted first before it is multiplied. Cool.
I'll also add that I didn't realize you can use the plus operator to add a row and column vector to create a matrix. Good stuff.
After testing, I realized your code worked for the specific example that I gave, but for the general loop there is a small correction in the first line. Many thanks to providing the vectorization concept/framework.
irow = (0:(NoBlocks-1))*(BS-ptsOL)+1;
icol = (0:BS-1)';
idxMat = irow+icol;
DataMatrix = DataVector(idxMat);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by