我想创建一个 4 维数组,每行包含随机数量的连续元素。这些应该始终从第一列开始并以随机列结束。 示例:
array(:,:,1,1) = [ 1 1 1 0 0 0;
1 1 0 0 0 0;
1 1 1 1 1 0;
... ]
可以用 3 个 for 循环做到这一点,但效率很低:
array = zeros(n,n,n,n);
for i= 1:n
for j = 1:n
for k =1:n
rows = ceil(n*rand());
array(k,1:rows,j,i) = 1;
end
end
end
有人能找到更好的解决方案吗?谢谢!!
最佳答案
简单直接的方法(虽然可能不是真正随机的)
rows = 8; %%// Number of rows
cols = 7; %%// Number of columns
ch3 = 3; %%// Number of elements in the 3rd dimension
ch4 = 2; %%// Number of elements in the 4th dimension
array = sort(round(rand(rows,cols,ch3,ch4)),2,'descend')
Bsxfun 方法(如下面的基准测试结果所示,速度要快得多,而且是真正随机的)
%%// Sizes
rows = 8; %%// Number of rows
cols = 7; %%// Number of columns
ch3 = 3; %%// Number of elements in the 3rd dimension
ch4 = 2; %%// Number of elements in the 4th dimension
%%// Get a 2D array with every row starting with a one
rows2 = rows*ch3*ch4;
a1 = reshape(1:rows2*cols,rows2,[]);
col = randi(cols,[1 rows2]);
b1 = bsxfun(@plus,(col-1)*rows2,1:rows2)';%//'
out = bsxfun(@le,a1,b1);
%%// Rearrange those to 4D
a2 = reshape(out',[rows*cols ch3 ch4]);%//'
a3 = reshape(a2,cols,rows,ch3,ch4);
array = permute(a3,[2 1 3 4]);
基准测试结果
我们正在将上述两种方法与 Rody 的方法进行比较。
Datasize I:
rows = 80; %// Number of rows
cols = 70; %// Number of columns
ch3 = 30; %// Number of elements in the 3rd dimension
ch4 = 2; %// Number of elements in the 4th dimension
Results:
Elapsed time with SORT approach is: 0.0083445sec
Elapsed time with BSXFUN approach is: 0.0021sec
Elapsed time with RODY approach is: 0.0063026sec
Datasize II:
rows = 80; %// Number of rows
cols = 70; %// Number of columns
ch3 = 30; %// Number of elements in the 3rd dimension
ch4 = 20; %// Number of elements in the 4th dimension
Results:
Elapsed time with SORT approach is: 0.07875sec
Elapsed time with BSXFUN approach is: 0.012329sec
Elapsed time with RODY approach is: 0.055937sec
Datasize III:
rows = 800; %// Number of rows
cols = 70; %// Number of columns
ch3 = 30; %// Number of elements in the 3rd dimension
ch4 = 20; %// Number of elements in the 4th dimension
Results:
Elapsed time with SORT approach is: 0.87257sec
Elapsed time with BSXFUN approach is: 0.17624sec
Elapsed time with RODY approach is: 0.57786sec
Datasize IV:
rows = 800; %// Number of rows
cols = 140; %// Number of columns
ch3 = 30; %// Number of elements in the 3rd dimension
ch4 = 20; %// Number of elements in the 4th dimension
Results:
Elapsed time with SORT approach is: 1.8508sec
Elapsed time with BSXFUN approach is: 0.35349sec
Elapsed time with RODY approach is: 0.71918sec
从这些发现得出的结论是,bsxfun
看起来是可行的方法,除非您想要处理数十亿个元素,正如 Rody 解决方案产生的内存基准测试结果所暗示的那样。
关于arrays - matlab数组创建随机连续的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22556693/