- STEP 1: Creting a matrix of indices
- STEP 2: Then using logical indexing to fill the ones
Vectorize scalar and colon
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
William Sherwin
il 30 Ago 2024
Modificato: Walter Roberson
il 1 Set 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 Commenti
Risposta accettata
Rahul
il 30 Ago 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.
Più risposte (1)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!