Find Min Value in MATLAB Array: No Built-in Functions

  • Thread starter Thread starter John31
  • Start date Start date
  • Tags Tags
    Matlab Value
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 3K views
John31
Messages
5
Reaction score
0

Homework Statement


I have an array of numbers in MATLAB which I want to located the minimum y-value but output the corresponding x value. (I can explain better if needed) I cannot use a bulit in function so I have tried to write my own. This is what I got so far.


The Attempt at a Solution



Code:
function [m n] = recursiveMin(A)

size = length(A);
if isempty(A)
    m = [];
    n = [];
elseif size == 1
    m = A(1);
    n = 1;
else
    A(1) = max;
    for
        %this is where I am stuck
        
    end
    
end
 
Physics news on Phys.org
Thanks for putting your code in [ code] tags!
John31 said:

Homework Statement


I have an array of numbers in MATLAB which I want to located the minimum y-value but output the corresponding x value. (I can explain better if needed) I cannot use a bulit in function so I have tried to write my own. This is what I got so far.


The Attempt at a Solution



Code:
function [m n] = recursiveMin(A)

size = length(A);
if isempty(A)
    m = [];
    n = [];
elseif size == 1
    m = A(1);
    n = 1;
else
    A(1) = max;
    for
        %this is where I am stuck
        
    end
    
end

Why are you doing this recursively? Once you know the size of the array, you can use a for loop to iterate through it and find the smallest value.

Your function doesn't need to return a different array - just the smallest value it found.

The basic algorithm is to set a variable min to the first value in the array, then loop through the rest of the array elements. In each iteration if the value of A(i) is less than min, reset min to the value. When the loop finishes, min will have been set to the smallest value in the array and you can return that value.