Finding position of value in an array

7 vues (au cours des 30 derniers jours)
sawasawa
sawasawa le 7 Avr 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?

Réponse acceptée

Cris LaPierre
Cris LaPierre le 7 Avr 2021
Modifié(e) : Cris LaPierre le 7 Avr 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.

Plus de réponses (1)

Julius Muschaweck
Julius Muschaweck le 7 Avr 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by