Finding the maximum of a vector using only for loop and the routine length

1 view (last 30 days)
Dear all,
I have been struggling with the programming of this script. I am trying to find the maximum number of a row vector, using only the routine length. So I have written the following script :
clear all, clc
v = [ 1 5 6 23 43 5 2 5 2 23 53 45 6 3 4] ;
number = 0 ;
max_number = 0 ;
for k = 1: length(v) -2
if v(k+1) > v(k) && v(k+1) > v(k+2)
number = v(k+1) ;
elseif v(k) > v(k+1) && v(k) > v(k+2)
number = v(k) ;
elseif v(k+2) > v(k+1) && v(k+2) > v(k)
number = v(k+2) ;
end
number
end
my problem is that matlab is taking comparing every 3 elements with each other... what can I do about it?
thanls alot
  1 Comment
Walter Roberson
Walter Roberson on 24 Oct 2020
The problem cannot be solved using only the routine length(). In MATLAB, comparing two numbers is a function call, and it is not possible to sort two numbers without comparing them.

Sign in to comment.

Answers (1)

KSSV
KSSV on 24 Oct 2020
v = [ 1 5 6 23 43 5 2 5 2 23 53 45 6 3 4] ;
n = length(v) ;
themax = 0 ;
pos = 1 ;
for i = 1:n
if v(i)> themax
themax = v(i) ;
pos = i ;
end
end
% check
[val,idx] = max(v)
[themax, pos]
  4 Comments

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!