MATLAB: Problems with min and max functions

functionsmaximum valueminimum value

I am currently doing a project where I have to make x and y equal to 100 random numbers, and then find the max and min of both x and y. I have a maximum value function and a minimum value function, but for some reason, whenever I run the code, nothing appears in the command window. No errors are showing up, so I am not quite sure why nothing is being displayed.
%Generate two arrays of 100 numbers each
x=randi([-9999,9999],10,10);
y=[];
y=[y,2.5+1*rand(10)]
%%
%Process the two arrays and determine:
%The largest and smallest values in x and y:
function max=maxval(x)
x=randi([-9999,9999],10,10);
i=length(x);
max=(x(1));
if (max)<(x(i))
max=(x(i))
end
disp(max)
end
function min=minval(x)
x=randi([-9999,9999],10,10);
min=x(1)
if min>(x(i))
min=(x(i))
end
end

Best Answer

  • Since you are defining your function as having a input x, you do not need to redfine it within your function. You can also achieve what you are asking without having to create any functions since max and min are already built-in to MATLAB, which brings up another point of what to avoid. You should try to stay away from using variables that are already defined as functions.
    Unless there is any reason that you need x and y to be 10x10 arrays it would make the use of max and min simplier if you make x and y vector-arrays with 100 elements.
    x = randi([-9999,9999],100,1);
    y = 2.5+rand([100,1]);
    minX = min(x);
    maxX = max(x);
    minY = min(y);
    maxY = max(y);
    If you need to create a function to accomplish this task, try the following. It will also easily handle array inputs as well as vectors.
    function [Min, Max] = MinMax(value)
    % Capitalizing the output variables to prevent unwanted behaviour when using built-in min and max functions.
    Min = min(value(:));
    Max = max(value(:));
    end
    Do the following to use your this function.
    x = randi([-9999,9999],10,10);
    y = 2.5+rand(10);
    [minX, maxX] = MinMax(x);
    [minY, maxY] = MinMax(y);