Filter löschen
Filter löschen

Finding position of value in an array

3 Ansichten (letzte 30 Tage)
sawasawa
sawasawa am 7 Apr. 2021
Bearbeitet: Cris LaPierre am 7 Apr. 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?

Akzeptierte Antwort

Cris LaPierre
Cris LaPierre am 7 Apr. 2021
Bearbeitet: Cris LaPierre am 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.

Weitere Antworten (1)

Julius Muschaweck
Julius Muschaweck am 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by