Write a function [M] = myMax(A), where M is the maximum value in an array A. Don't use the built-in MATLAB function max. Then write a function (M) = myNMax(A,N) where M is an array consisting of the N largest elements in A using the myMax function.

6 views (last 30 days)
My myMax function looks like this:
function [M] = myMax(A)
for i=1:(length(A)-1)
M=A(i);
if A(i+1)>A(i)
M=A(i+1);
end
end
end
I have no idea how to use this to make [M]=myNMax(A,N).

Accepted Answer

Marc Jakobi
Marc Jakobi on 5 Oct 2016
Edited: Marc Jakobi on 5 Oct 2016
I'm assuming this is a homework assignment, so I won't give you a full answer. Here are some hints as to how you could do it:
- initialize M
- use myMax(M) to find out if A(i) is greater than the previously stored values in M
- if it is, append the new value to M
- if M has more than N values, delete the first value

More Answers (1)

James Tursa
James Tursa on 5 Oct 2016
Edited: James Tursa on 5 Oct 2016
Thanks for making an attempt and posting your code. It is unclear from your post if the function is supposed to operate on arbitrary sized arrays (as written), or only on vectors. I will assume arrays since that is what you wrote.
Your myMax function should be using something like numel(A) instead of length(A). Otherwise you won't be testing all of the elements. E.g.,
>> A = rand(3,4);
>> length(A)
ans =
4
>> numel(A)
ans =
12
As you can see from above, using length(A) will not result in iterating through all of the elements.
Also, as written, your myMax function only gets the max of the last two values tested in your for loop, not the overall max. You need to move that M = A(i) stuff outside the loop. E.g., these lines:
for i=1:(length(A)-1)
M=A(i);
if A(i+1)>A(i)
should look something like this instead:
M = A(1);
for i=1:(numel(A)-1)
if A(i+1)>M
For the myNMax function, there are various ways to code this. Did your instructor give you any hints as to what methods/algorithms to use? E.g., using sorting or recursion? Have you made any attempts at this yet?

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!