matlab:不带循环的不同大小子阵列的和值

时间:2014-06-22 07:25:02

标签: 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和其他方法提出解决方案。 但是我能想到的所有解决方案都要求各部分具有相同的大小 - 事实并非如此:(

有什么想法吗?

最好的, Jens Henrik

2 个答案:

答案 0 :(得分:2)

使用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 );

答案 1 :(得分:0)

bsxfun替换你的for-loop部分的方法 -

t1 = bsxfun(@le,1:size(A,1),posIdx(2:end)) & bsxfun(@ge,1:size(A,1),posIdx(1:end-1));
t1 = t1';
t2 = A(:,ones(1,size(t1,2))).*t1;
t2(~t1)=nan;
Amin = nanmin(t2);
Amax = nanmax(t2);