serveral normrnd without a loop
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
per isakson
le 15 Juin 2019
Modifié(e) : per isakson
le 16 Juin 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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!