'Indexing vectors in Matlab

I am used to working with python, and am just getting used to Matlab. I am trying to write a foor loop in Matlab similar to this

x_temp=x[0]
for i in range(0,400):
   if x[i]>=x_temp:
      x_temp=x[i]
print(x_temp)

I tried

N=401;
x=linspace(-20,20,N);
dt = 0.0002;
t=0:dt:2;
x_temp=x(0);
for j=2: lenght(t)
  if x(j)>=x_temp
    x_temp=x(j);
end
end
print(x_temp);

but I get an error saying 'Array indices must be positive integers or logical values.' Could anyone please help answer how I should index the vectors properly in matlab?



Solution 1:[1]

Arrays start at 1 in matlab, not 0 like in python. It's kind of a pain but you'll get used to it.

It's not really clear what you are trying to compute here since it's just a fragment, but it looks like you want the largest element in the array. No need for a for loop, just use the max function on the subset of the array you want to test:

[value, index] = max( x(2:length(t)) ) ;

In general what makes matlab better than other languages for math/science is the powerful built in functions. Never write a for loop before you check if there's a simple function or one-line vector operation that gives the same result (and in most cases, much quicker).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1