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 visualizaciones (últimos 30 días)
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).

Respuesta aceptada

Marc Jakobi
Marc Jakobi el 5 de Oct. de 2016
Editada: Marc Jakobi el 5 de Oct. de 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

Más respuestas (1)

James Tursa
James Tursa el 5 de Oct. de 2016
Editada: James Tursa el 5 de Oct. de 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?

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by