How to return the maximum value of a vector without using the built in function max(x)?

I have to calculate the maximum value of a vector, x, without using the built in function, only using basic mathematical,
relational, and logical operations. Then the maximum must be stored to a variable, y. The script must work with any vector assigned to x.

Answers (3)

Apparently, you also cannot use a built-in sort algorithm. That leaves you the option of coding your own bubble-sort algorithm, or the Quicksort (link) algorithm.
K = rand(5) ;
themax = -Inf;
row = 0;
column = 0;
for i = 1:size(K, 1)
for j = 1:size(K, 2)
if K(i, j) > themax
themax = K(i, j);
row = i;
column = j;
end
end
end
v = [12, 45, 7, 89, 34, 56];
largest = v(1);
for i = 2:length(v)
if v(i) > largest
largest = v(i);
end
end
disp(['Maximum value is: ', num2str(largest)]);
Maximum value is: 89

Asked:

on 30 Apr 2019

Community Treasure Hunt

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

Start Hunting!