フィルターのクリア

Vectorize scalar and colon

5 ビュー (過去 30 日間)
William Sherwin
William Sherwin 2024 年 8 月 30 日
編集済み: Walter Roberson 2024 年 9 月 1 日
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 件のコメント
William Sherwin
William Sherwin 2024 年 9 月 1 日
Thanks Rahul, Bill

サインインしてコメントする。

その他の回答 (1 件)

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by