Finding position of value in an array

7 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Cris LaPierre
Cris LaPierre il 7 Apr 2021
Modificato: Cris LaPierre il 7 Apr 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.

Più risposte (1)

Julius Muschaweck
Julius Muschaweck il 7 Apr 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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by