Finding position of value in an array

2 次查看(过去 30 天)
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?

采纳的回答

Cris LaPierre
Cris LaPierre 2021-4-7
编辑:Cris LaPierre 2021-4-7
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.

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by