serveral normrnd without a loop
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
per isakson
2019-6-15
编辑:per isakson
2019-6-16
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!