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.

10 次查看(过去 30 天)
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).

采纳的回答

Marc Jakobi
Marc Jakobi 2016-10-5
编辑:Marc Jakobi 2016-10-5
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

更多回答(1 个)

James Tursa
James Tursa 2016-10-5
编辑:James Tursa 2016-10-5
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?

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by