Using find in a loop

Hello,
I have a problem with the code below. I am trying to get the maximum values of the vector I and its indices. I find the maximum values without problems and store them in Maxi. Finding the indices does not work. The code below gives a 1+15 double filled with [3,2,1,3,3,3,2,1,1,1,3,3,3,2,1] instead of [3, 3, 3, 4,7, 8,8, 8, 9, 10, 13, 14, 15, 15, 15]. Could anyone please let me know what I am doing wrong?
I = [1, 2, 4, 3,3,3,5, 10,8,7, 2,4, 5, 6, 8,6,5 ];
for ii = 1:15
Maxi(ii) = max(I(ii:(ii+2)));
I_Maxi(ii) = find(I(ii:(ii+2)) == max(I(ii:(ii+2))));
end
I want only to find the first index within the window ii:ii+2 of the maximum value of I and store it. Is this somehow possible?
Thank you for your help.

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 7 月 28 日
編集済み: Azzi Abdelmalek 2013 年 7 月 28 日

0 投票

Use find(expression,1)
I = [1, 2, 4, 3,3,3,5, 10,8,7, 2,4, 5, 6, 8,6,5 ];
for ii = 1:15
Maxi(ii) = max(I(ii:(ii+2)));
I_Maxi(ii) = find(I(ii:(ii+2)) == max(I(ii:(ii+2))),1);
end

3 件のコメント

Silke
Silke 2013 年 7 月 29 日
Hi Azzi,
Thank you for your reply. Unfortunately, the code that you have posted does not find the correct values. It finds the same values for I_Maxi then as with my code. Do you have another idea?
Cheers,
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 7 月 29 日
編集済み: Azzi Abdelmalek 2013 年 7 月 29 日
I = [1, 2, 4, 3,3,3,5, 10,8,7, 2,4, 5, 6, 8,6,5 ];
for ii = 1:15
[b,c] = max(I(ii:(ii+2)));
maxi(ii)=b;
idxi(ii)=c+ii-1
end
%or
I = [1, 2, 4, 3,3,3,5, 10,8,7, 2,4, 5, 6, 8,6,5 ];
n=numel(I)-2
for ii = 1:n
[maxi(ii),idxi(ii)] = max(I(ii:(ii+2)));
end
idxi=idxi+(0:n-1)
Silke
Silke 2013 年 7 月 29 日
Thanks a lot. It is working now fine.

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

Andrei Bobrov
Andrei Bobrov 2013 年 7 月 28 日
編集済み: Andrei Bobrov 2013 年 7 月 29 日

0 投票

I = [1, 2, 4, 3,3,3,5, 10,8,7, 2,4, 5, 6, 8,6,5 ];
for ii = 15:-1:1
[Maxi(ii,1),jj]= max(I(ii:(ii+2)));
I_Maxi(ii,1) = jj + ii -1;
end
OR
ii = (0:numel(I)-3)';
[Maxi,jj] = max(I(bsxfun(@plus,1:3,ii)),[],2);
I_Maxi = jj + ii;

2 件のコメント

Silke
Silke 2013 年 7 月 29 日
Hi Andrei,
Thanks for the answer. Unfortunately, your code gives the same result as mine and Azzi's. Is there no way to find the correct indices from I and not the indices of I(1:3) that are always between 1 and 3?
Thank you, Silke
Andrei Bobrov
Andrei Bobrov 2013 年 7 月 29 日
Corrected.

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2013 年 7 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by