Vectorize scalar and colon

4 次查看(过去 30 天)
THIS IS SOMETHING I CAN DO OK WITH A for LOOP, BUT I AM TRYING TO VECTORIZE TO SPEED IT UP:
I ENTER THE FOLLOWING CODE:
p=[.25 .25 .25 .45 .45 .45];
L=length(p);
Nit=10;
preindit=zeros(L,Nit);
l=1:L;
targetit=round(p(l).*Nit);
preindit(l,1:targetit(l))=1;
THIS GIVES THE RESULT:
targetit =
3 3 3 5 5 5
preindit =
1 1 1 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
WITH THE WARNING
Warning: Colon operands must be real scalars. This warning will become an error in a future release.
BUT WHAT I WAS HOPING FOR WAS:
preindit =
1 1 1 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0
IE MATLAB IS APPLYING THE targetit-value FOR l=1 TO ALL ROWS OF preindit, NOT JUST THE FIRST ROW. MATLAB DOES NOT DO THAT, OR GIVE THE WARNING ABOUT SCALARS, WHEN THE SAME CODE IS EMBEDDED IN A LOOP.
WHAT AM I DOING WRONG WITH THE VECTORIZATION PLEASE?
NB the full thing I am trying to do is on a very large scale, with multiple different values of p and Nit, so simply typing in the array I want is not a sensible option, it has to be done by a loop (slow) or vectorization, I think. The challenge seems to be to get MATLAB to recognize that each possible value of targetit(1:L) is a real scalar.

采纳的回答

Rahul
Rahul 2024-8-30
I understand that you are trying to vectorize to speed up the code and obtain the desired result mentioned in the question.
You can do that by following this method:
  • STEP 1: Creting a matrix of indices
  • STEP 2: Then using logical indexing to fill the ones
p = [.25 .25 .25 .45 .45 .45];
L = length(p);
Nit = 10;
preindit = zeros(L, Nit);
targetit = round(p .* Nit);
% STEP 1
indices = repmat(1:Nit, L, 1);
disp(indices);
% STEP 2
preindit(indices <= targetit') = 1;
You can refer to the following documentations to know more:
Hope this helps! Thanks.

更多回答(1 个)

KSSV
KSSV 2024-8-30
A = zeros(6,10) ;
A(:,1:3) = 1 ;
A(4:6,4:5) = 1;

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by