MATLAB Answers

xena42
0

serveral normrnd without a loop

Asked by xena42
on 14 Jun 2019
Latest activity Commented on by xena42
on 16 Jun 2019
Hey there :)
I would like to create a vector that is made of several normal distributions without using a loop.
Here is the code with the loop:
% my values so far
sig=0.43;
mu=[-3.9, -1.5, 0.3, 2.1];
length=[1, 5, 9, 5];
% loop
req_zeros=max(length);
x=nan(numel(mu),req_zeros);
for k=1:numel(mu)
x(k,:)=[normrnd(mu(k),sig,[1,length(k)]), zeros(1,req_zeros-length(k))];
end
% the vector im looking for is:
x=x(x~=0).';
Can anyone tell me how to get to x without using a loop at all?
I'm very thankful for any help!

  0 Comments

Sign in to comment.

1 Answers

Answer by per isakson
on 15 Jun 2019
Edited by per isakson
on 16 Jun 2019
 Accepted Answer

What about this?
>> cell2mat( arrayfun( @(m,l) normrnd( m, sig, [1,l] ), mu, len, 'uni',false ) )
ans =
Columns 1 through 7
-4.1537 -1.6196 -1.3182 -2.2182 -1.2972 -2.0215 0.32846
Columns 8 through 14
0.58051 0.44064 0.76553 0.73261 0.02011 0.41053 -0.10608
Columns 15 through 20
-0.26837 2.4977 2.1 2.0764 2.4918 2.3557
I renamed your length to len because length is a Matlab function. Sorry for the lower case L.
No, the numbers are in a different order.
The script below produces the same result as your script
rng('default')
mx = max( len );
cac = arrayfun( @(m,l) [normrnd(m,sig,[1,l]),zeros(1,mx-l)], mu, len, 'uni',false );
y = reshape( cell2mat(reshape(cac,[],1)), 1,[] );
y(y==0)=[]; % There is a vanishingly small chance that normrnd() returns the value zero.

  1 Comments

xena42
on 16 Jun 2019
Thank you so much!
I came up with this now, which should do pretty much the same, if i understand your code correctly:
(unsing len instead of length as you suggested)
mu=repmat(mu,max(len),1);
sig=sig*ones(size(mu));
logicCut=cumsum(repmat(len, max(len),1)) <= len.^2; % true for numbers I'n interested in
x=normrnd(mu,sig,size(mu));
x=x(logicCut); % cuts away unwanted numbers

Sign in to comment.



Translated by