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

  • Thread starter Thread starter John31
  • Start date Start date
  • Tags Tags
    Matlab Value
Click For Summary
The discussion centers on finding the minimum value in a MATLAB array without using built-in functions. The user is attempting to create a recursive function but is struggling with the implementation. A suggestion is made to use a for loop instead of recursion, emphasizing that the function should return only the smallest value found. The proposed algorithm involves initializing a variable to the first array element and iterating through the array to update this variable when a smaller value is encountered. The conversation highlights the importance of simplifying the approach to achieve the desired outcome efficiently.
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.
 

Similar threads

Replies
2
Views
1K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 13 ·
Replies
13
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 10 ·
Replies
10
Views
2K