how to find max value of a function with a for loop

2 visualizaciones (últimos 30 días)
Hi,
I have a vector x and a vector y with both vectors having 10 elements and I have a function which uses a for loop to give a value to a variable e with each respective value of y and x. The for loop works as such;
for i=1:length(x)
e=y(i)-(m*x(i)+b)
end
and I want to display only the max value of e in the command window and the respective x and y elements that correspond to it. How would I do this?

Respuesta aceptada

James Tursa
James Tursa el 10 de Feb. de 2020
Make e a vector. E.g.,
for i=1:length(x)
e(i) = y(i) - (m*x(i)-b); % <-- Are you sure that isn't supposed to be (m*x(i) + b) with a plus?
end
Then use the max function:
[E,Z] = max(abs(e));
E will contain the max (abs), and Z will contain the index of the max, so
e(Z) is the max (abs)
x(Z) is the x of the max
y(Z) is the y of the max
  1 comentario
Abdur Rahman Hashmi
Abdur Rahman Hashmi el 10 de Feb. de 2020
Thanks! Yeah i wrote it down wrong, it is with a plus. I'll edit my question so it will show up correctly.

Iniciar sesión para comentar.

Más respuestas (1)

Sindar
Sindar el 10 de Feb. de 2020
Loop isn't necessary unless you can't store the data in memory:
e=y-(m*x-b);
[e_max,idx] = max(e);
x_max = x(idx);
y_max = y(idx);

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by