Problems with min and max functions

12 visualizzazioni (ultimi 30 giorni)
Kyle Donk
Kyle Donk il 17 Gen 2020
Commentato: Kyle Donk il 17 Gen 2020
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
  2 Commenti
stozaki
stozaki il 17 Gen 2020
Hello,
What version of MATLAB are you using? I execute your program 1000 times using R2019a Update 3 and no problem.
I attached the results printed.
Regards,
stozkai
Kyle Donk
Kyle Donk il 17 Gen 2020
I just got it to work. Thank you for your help!

Accedi per commentare.

Risposta accettata

Allen
Allen il 17 Gen 2020
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);

Più risposte (0)

Categorie

Scopri di più su Tables in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by