我想知道是否可以获得不同大小子数组的最小/最大值 在 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 等提出解决方案。 但我能想到的所有解决方案都要求各部分具有相同的大小 - 但事实并非如此:(
有什么想法吗?
最好的, 延斯·亨里克
最佳答案
使用cumsum
和accumarray
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/