- STEP 1: Creting a matrix of indices
- STEP 2: Then using logical indexing to fill the ones
Vectorize scalar and colon
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
William Sherwin
le 30 Août 2024
Modifié(e) : Walter Roberson
le 1 Sep 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.
0 commentaires
Réponse acceptée
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:
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:
'Array Indexing': https://www.mathworks.com/help/releases/R2024a/matlab/math/array-indexing.html?searchHighlight=logical%20indexing&s_tid=doc_srchtitle
Hope this helps! Thanks.
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!