matlab:无回路的不同大小子阵列的总和

matlab:无回路的不同大小子阵列的总和,matlab,max,vectorization,min,arrays,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)

我想知道是否有可能获得不同大小子阵列的最小/最大值 在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中矢量化这个循环

% 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
我尝试使用arrayfun、remap、bsxfun和其他工具提出解决方案。 但我能想到的所有解决方案都要求截面尺寸相等,但事实并非如此:(

有什么想法吗

最好的,
Jens Henrik使用cumsum和


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

+1使用accumarray做得很好,可能比bsxfun实现快得多。您是否注意到OP与各部分重叠了一个元素?除此之外,您的方法是正确的(当我说您的方法时,我正在基于此编写答案)@LuisMendo有趣的一点。我没有注意到这个细节。它确实让事情变得有点复杂……我会看看是否可以解决。我认为
Amax=max(Amax,a([find(pos01);end]);
会起作用。+1Accumaray()这正是我搜索的命令-太好了。谢谢Shai,谢谢Luis-你的评论真的很有帮助!我会测试一下,如果这在一个简单的for循环中带来了希望的加速。这很有趣,但恐怕不是使用它的正确位置:(a)生成的代码很难理解。(b)它使用了太多的内存o(n^2)@Shai感谢您的反馈。同意您的看法,解决此问题的速度确实较慢。但是,
bsxfun
将始终使用
o(n^2)
,如果提供足够的计算资源和内存带宽,它可能会很有用。此
o(n^2)
内存要求适用于所有使用
bsxfun
的解决方案。在解释部分,有时我会让提问者主动询问代码的具体部分,如果有任何疑问。实际上
bsxfun
将始终使用o(n^2)但在许多情况下,这是合理的:恐怕这里不是这样。我觉得对于这个特定的任务,
bsxfun
不是正确的工具,对于许多其他任务,
bsxfun
是非常有用的,我认为每个Matlab编程人员都应该让自己熟悉。+1对于正确处理OP se中的一个元素重叠ems至want@LuisMendo事实上,我根本没有处理这个问题,这段代码只替换for循环部分。欣赏+1!:)仍然想知道是否有一个矢量化的解决方案可以击败for循环部分。你真的需要在最后/第一个元素中重叠部分吗?我可以避免重叠。accumarray正在做这项工作。伟大的