serveral normrnd without a loop

3 visualizzazioni (ultimi 30 giorni)
xena42
xena42 il 14 Giu 2019
Commentato: xena42 il 16 Giu 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!

Risposta accettata

per isakson
per isakson il 15 Giu 2019
Modificato: per isakson il 16 Giu 2019
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 Commento
xena42
xena42 il 16 Giu 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements 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!

Translated by