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

1 Ansicht (letzte 30 Tage)
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 Kommentar
Walter Roberson
Walter Roberson am 24 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

KSSV
KSSV am 24 Okt. 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 Kommentare
KSSV
KSSV am 24 Okt. 2020
Thank sis accepting/ voting the answer.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by