How can I vectorize this for loop?

조회 수: 2 (최근 30일)
Matthew Casiano
Matthew Casiano 2021년 9월 9일
편집: Matthew Casiano 2021년 9월 10일
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