matlab:不循环不同大小子数组的总和

标签 matlab max vectorization min arrays

我想知道是否可以获得不同大小子数组的最小/最大值 在 matlab 中不使用循环。

% create a 1D vector with arbitory floating point values
A = rand(100,1,'double');

% get start indexes of sections of A (eg. A>0.9)
pos01 = A>0.9;
posIdx= [1;find(pos01);size(A,1)];

% if 1 or size(A,1) where not required, remove them
posIdx = unique(posIdx); 

% min/max all sections:
for ix=1:size(posIdx,1)-1
    Amin(ix) = min(A(posIdx(ix):posIdx(ix+1)));
    Amax(ix) = max(A(posIdx(ix):posIdx(ix+1)));
end

如果您有一个非常大的向量 A 和很多部分,那么最后一行可能会非常慢。 我想知道如何在 matlab 中向量化这个循环。

我尝试使用 arrayfun、remap、bsxfun 等提出解决方案。 但我能想到的所有解决方案都要求各部分具有相同的大小 - 但事实并非如此:(

有什么想法吗?

最好的, 延斯·亨里克

最佳答案

使用cumsumaccumarray

A = rand(100,1,'double');
pos01 = A > 0.9;
subs = ( pos01(1) == 0 ) + cumsum( pos01(:) ); % convert posIdx to subs. note the special treatment of the first entry. 
Amin = accumarray( subs, A, [], @min );
Amax = accumarray( subs, A, [], @max );

关于matlab:不循环不同大小子数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24349029/

相关文章:

python - 如何使用 numpy 从两个一维数组生成 bool 二维数组

matlab - 在 MATLAB 中,每次值从 1 变为 0 时如何查找向量中的索引?

c++ - MATLAB 上的矩阵操作到 C++ 或 OpenCV

mysql - 了解一些 MySQL 优化技巧

mysql - 使用连接不返回行选择最大值

python - 如何同时使用窗口大小裁剪 numpy 数组的每个元素而不循环遍历每个像素?

matlab - 在 MATLAB 中不使用 for 循环将特定矩阵位置替换为数组值

MATLAB:更快的零矩阵预分配

SQL 使用 MAX() 函数选择不在 Group By 中的字段

matlab - 将 C 风格代码转换为 Matlab