Effacer les filtres
Effacer les filtres

Vectorize scalar and colon

5 vues (au cours des 30 derniers jours)
William Sherwin
William Sherwin le 30 Août 2024
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.

Réponse acceptée

Rahul
Rahul le 30 Août 2024
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 commentaire
William Sherwin
William Sherwin le 1 Sep 2024
Thanks Rahul, Bill

Connectez-vous pour commenter.

Plus de réponses (1)

KSSV
KSSV le 30 Août 2024
A = zeros(6,10) ;
A(:,1:3) = 1 ;
A(4:6,4:5) = 1;

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by