How can I vectorize this for loop?

2 次查看(过去 30 天)
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

采纳的回答

TADA
TADA 2021-9-9
irow = (0:(NoBlocks-1))*ptsOL+1;
icol = (0:BS-1)';
idxMat = irow+icol;
DataMatrix = DataVector(idxMat);
  1 个评论
Matthew Casiano
Matthew Casiano 2021-9-9
编辑:Matthew Casiano 2021-9-10
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);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by