I have 2 "if" conditions and i need to apply it to multiple rows of data.

조회 수: 2 (최근 30일)
Hi. I have 2 sets of data as below:
D=
234
54
3567
453
645
T=
234
557
48
957
4362
I need to do 2 if conditions for the 2 data like
if D>400 & T>600
F=1;
else
F=0;
end
but when I do that, it only takes the top value of D and T. I need it such that if D is 5 rows of single column value, the F values should results in 5 rows of single column too.

채택된 답변

MathReallyWorks
MathReallyWorks 2017년 5월 28일
Hello Izza ismail,
Your F is a variable. To get F same as D and T, your F should be an array of length 5. Hence you need to introduce a for loop to operate on all elements.
Use this:
D= [234 54 3567 453 645];
T= [234 557 48 957 4362];
for i=1:5
if D(i)>400 & T(i)>600
F(i)=1;
else
F(i)=0;
end
end
disp(F');
It works as per your requirement.
  댓글 수: 3
Stephen23
Stephen23 2017년 5월 28일
편집: Stephen23 2017년 5월 28일
"Hence you need to introduce a for loop to operate on all elements."
This is incorrect. Using a loop is a total waste of MATLAB's ability to work with arrays. See my answer for a much simpler and much more efficient solution.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2017년 5월 28일
편집: Stephen23 2017년 5월 28일
Do not waste your time learning inefficient and ugly code that relies on loops and if-s. These are not required, not matter how many other beginners will tell you so. All you need is a simple one-line piece of code:
>> F = D>400 & T>600
F =
0
0
0
1
1
Learning how to operate on whole arrays at once, as my answer shows, is one of the first steps to learning how to use MATLAB efficiently. Solving every problem by using ugly loops is necessary for low-level languages like C++, but is a total waste of time in a high-level language like MATLAB. You can learn these kind of very basic MATLAB concepts by doing the introductory tutorials, which are highly recommended for all beginners:
And also read these:
  댓글 수: 1
MathReallyWorks
MathReallyWorks 2017년 5월 28일
Hey Stephen,
Thanks for your feedback. I liked your answer. This is great. And thanks for those important links too.

댓글을 달려면 로그인하십시오.

카테고리

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