How to remove a value from a vectort and revaluate it?

3 ビュー (過去 30 日間)
Danielle
Danielle 2012 年 11 月 27 日
Hi
I'm trying to create a vector from a random number drawn from a normal distribution.
maxiter=1000;
M=zeros(maxiter,1);
M=(0.8+0.8*randn(maxiter,1));
Because negative numbers don't make any biological sense in this case, I would like have the negative values redrawn from the randn
if M<0;
Mtemp=M;
while Mtemp<0;
Mtemp=(0.8+0.8*randn);
M=Mtemp;
end
else M=M;
end;
This does not seem replace any of the negative values. Thanks for the help!
  1 件のコメント
David C
David C 2012 年 11 月 27 日
I believe you need to look into logical indexing.
Matlab's specialty when dealing with matrices and vectors is logical indexing, so instead of your if/else block, you can simply use M(M<0)=[];

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

回答 (2 件)

Thomas
Thomas 2012 年 11 月 27 日
Just editing your code..
maxiter=1000;
M=zeros(maxiter,1);
M=(0.8+0.8*randn(maxiter,1));
for ii=1:length(M)
if M(ii)<0;
Mtemp=0.8+0.8*randn;
while Mtemp<0;
Mtemp=(0.8+0.8*randn);
M(ii)=Mtemp;
end
M(ii)=Mtemp;
end
end

Matt Fig
Matt Fig 2012 年 11 月 27 日
編集済み: Matt Fig 2012 年 11 月 27 日
There is no need to pre-allocate M, as M is not built in a FOR loop. You are just overwriting the pre-allocation in one call, so it is not necessary at all.
maxiter = 1000;
M = 0.8 + 0.8*randn(maxiter,1);
idx = M<0;
while any(idx)
M(idx) = 0.8+0.8*randn(sum(idx),1);
idx = M<0;
end

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by