Using a function with a loop for finding the maximum value and its index.

Hello!
I am fairly new to MATLAB and am struggling with the topic of loops. A homework of mine is the following:
I need to write a function that finds the max value and its index in a data vector. Also, I am not allowed to use the built-in max function or any other function that relates to the order of magnitudes of elements.
So far I have this function:
function[Max1, MaxI1] = VecMax(Vec1)
Max1 = Vec1(1);
MaxI1 = 1;
while (MaxI1 < length(Vec1))
if(Vec1(MaxI1) > Max1)
Max1=Vec1(MaxI1);
end
MaxI1 = MaxI1 + 1 ;
end
end
Using this example
Vec1=[4 5 9 2 10 -1 4 0 3 12 4];
[Max1,MaxI1] = VecMax(Vec1);
I receive the correct Value for Max1 but still having issues with MaxI1.
Help would be really appreciated

回答 (1 件)

David Hill
David Hill 2022 年 10 月 13 日
Vec1=[4 5 9 2 10 -1 4 0 3 12 4];
[Max1,MaxI1] = VecMax(Vec1)
Max1 = 12
MaxI1 = 10
function[Max1, MaxI1] = VecMax(Vec1)
Max1 = Vec1(1);
MaxI1 = 1;
for k=2:length(Vec1)%use for-loop to cycle through entire array
if Vec1(k) > Vec1(k-1)
Max1=Vec1(k);
MaxI1=k;
end
end
end

4 件のコメント

Mike
Mike 2022 年 10 月 13 日
Thank you!
But a following up question why does this code not work for this example?
As a solution I get Max1 = 99 , MaxI2 =6
Vec1=[-100 0 200 30 50 99];
[Max1,MaxI1] = VecMax(Vec1)
Vec1=[-100 0 200 30 50 99];
[Max1,MaxI1] = VecMax(Vec1)
Max1 = 200
MaxI1 = 3
function[Max1, MaxI1] = VecMax(Vec1)
Max1 = Vec1(1);
MaxI1 = 1;
for k=2:length(Vec1)%use for-loop to cycle through entire array
if Vec1(k) > Max1
Max1=Vec1(k);
MaxI1=k;
end
end
end
David Hill
David Hill 2022 年 10 月 13 日
Yes!
Mike
Mike 2022 年 10 月 13 日
You guys are awesome! Thanks

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

カテゴリ

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

質問済み:

2022 年 10 月 13 日

コメント済み:

2022 年 10 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by