find max of a vector between two indice

17 ビュー (過去 30 日間)
Hajik zagori
Hajik zagori 2011 年 9 月 12 日
コメント済み: Andrei Keino 2017 年 8 月 15 日
Hi, I want a code to find the maximum number between two indice of a vector.
I have an indice vector and a data vector . For example my indice vector is :
A=[3 7 13]
and my data vector is:
B=[-5 3 -8 1 -7 2 -9 3 6 2 7 9 -4 2 6]
now the max number between indices 3 and 7 of vector B is number "2" .
and the max number between indices 7 and 13 of vector B is number "9".
So the output should be like a vector named C as follows:
C=[2 9]
I've been thinking on this for hours but haven't found any solution yet :(
Tnx in advance.
  1 件のコメント
Andrei Keino
Andrei Keino 2017 年 8 月 15 日
%
[M,I] = max(B(3:7);
I = I + 3;

サインインしてコメントする。

採用された回答

Lucas García
Lucas García 2011 年 9 月 12 日
>> C = arrayfun(@(x) max(B(A(x):A(x+1))),1:length(A)-1)
C =
2 9
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2011 年 9 月 12 日
Hi friends!
My part
C = cellfun(@max,mat2cell(B(A(1):A(end)),1,diff(A)+[1 0]))

サインインしてコメントする。

その他の回答 (3 件)

Sean de Wolski
Sean de Wolski 2011 年 9 月 12 日
Easiest, and likely fastest way is just to use a for-loop:
A=[3 7 13];
B=[-5 3 -8 1 -7 2 -9 3 6 2 7 9 -4 2 6];
nmax = length(A)-1;
maxes = zeros(1,nmax);
for ii = 1:nmax
maxes(ii) = max(B(A(ii):A(ii+1)));
end
TIMINGS Mac 2009b
A=[3 7 13];
B=[-5 3 -8 1 -7 2 -9 3 6 2 7 9 -4 2 6];
t1 = 0;
t2 = 0;
for ii = 1:100
tic
nmax = length(A)-1;
maxes = zeros(1,nmax);
for ii = 1:nmax
maxes(ii) = max(B(A(ii):A(ii+1)));
end
t1 = t1+toc;
tic
C = arrayfun(@(x) max(B(A(x):A(x+1))),1:length(A)-1);
t2 = t2+toc;
end
t2/t1
ans = 25.029
arrayfun takes about 25x longer on my system
  3 件のコメント
Sean de Wolski
Sean de Wolski 2011 年 9 月 12 日
I would write a new specific function that accepts A,B and spits out an answer. Then call it from where we need prettiness.
Lucas García
Lucas García 2011 年 9 月 12 日
Yes!

サインインしてコメントする。


Fangjun Jiang
Fangjun Jiang 2011 年 9 月 12 日
A=[3 7 13];
B=[-5 3 -8 1 -7 2 -9 3 6 2 7 9 -4 2 6];
C=zeros(1,numel(A)-1)
for k=1:numel(A)-1
C(k)=max(B(A(k):A(k+1)));
end

Hajik zagori
Hajik zagori 2011 年 9 月 12 日
Thank you very much Lucas , Fangjun and Sean.I checked them all and all three solutions worked perfectly.
I don't know which answer I'd better accept because all of them were good.
Anyway I guess I choose the first one.
Best Regards .
Hajik.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by