if statement for a matrix

조회 수: 2 (최근 30일)
Darpan Verma
Darpan Verma 2019년 3월 11일
답변: Darpan Verma 2019년 3월 11일
Hi my x-axis is a 1x72 matrix having values from 1 to 72.
y axis values are again 1x72 matrix having data values.
I want the "if loop" to go on for only those x values which are between 10 and 25, and plot x vs y for only those selected values (y axis data values corresponding to the values between 10 to 25). Could you please evaluate my code.
for i = 1:length(x)
if (x>10) && (x<25)
plot(x,y)
end
end

채택된 답변

Star Strider
Star Strider 2019년 3월 11일
Use ‘logical indexing’:
x = 1 : 72;
y = rand(1, 72);
mv = (x>10) & (x<25);
figure
plot(x(mv), y(mv))
grid
xlim([min(x) max(x)])
Experiment to get the result you want.

추가 답변 (2개)

Alex Mcaulley
Alex Mcaulley 2019년 3월 11일
You don't need the loop, just using logical indexing:
plot(x(x>10&x<25),y(x>10&x<25))

Darpan Verma
Darpan Verma 2019년 3월 11일
Thanks guys.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by