Finding position of value in an array

7 visualizaciones (últimos 30 días)
sawasawa
sawasawa el 7 de Abr. de 2021
Editada: Cris LaPierre el 7 de Abr. de 2021
I'm working on some code and here's a portion of it
clear all; close all; clc;
y = [-3.2628 -2.4774 -1.6920 -0.9066 -0.1212 0.6642 1.4496 2.2350 3.0204];
x=-2.8701;
for i=1:length(y)-1
if (x>=y(i) && x <=y(i+1))
x=i-1;
end
end
The answer i'm getting is
x =
4
I expect x=0. Is there anything I'm doing wrong?

Respuesta aceptada

Cris LaPierre
Cris LaPierre el 7 de Abr. de 2021
Editada: Cris LaPierre el 7 de Abr. de 2021
The first thing that jumps out to me is that you replace your x value with your counter value. As the loop progresses, your if statement is no longer comparing to x=-2.8701.
Perhaps you want it to stop after if finds the first true case? If so, add break after x=i-1 to stop the for loop.

Más respuestas (1)

Julius Muschaweck
Julius Muschaweck el 7 de Abr. de 2021
clear all; close all; clc;
y = [-3.2628 -2.4774 -1.6920 -0.9066 -0.1212 0.6642 1.4496 2.2350 3.0204];
x=-2.8701;
for i=1:length(y)-1
if (x>=y(i) && x <=y(i+1))
XXXX =i-1; % do not use x -- you will overwrite -2.8701 with 0, which
% will then match for i = 5
end
end

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