serveral normrnd without a loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
xena42
am 14 Jun. 2019
Kommentiert: xena42
am 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 Kommentare
Akzeptierte Antwort
per isakson
am 15 Jun. 2019
Bearbeitet: per isakson
am 16 Jun. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!