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

4 views (last 30 days)
Izza Ismail on 28 May 2017
Commented: MathReallyWorks on 28 May 2017
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 on 28 May 2017
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.

Izza Ismail on 28 May 2017
Thanks! However, how do i write the 'i' for as many times as D? Bcs my real data is in thousands and i'd like for it to just follow instead of me having to check the number. like
for i=1:numberof(D) ?
or. something like that.
MathReallyWorks on 28 May 2017
for i=1:length(D)
Stephen Cobeldick on 28 May 2017
"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.

Stephen Cobeldick on 28 May 2017
Edited: Stephen Cobeldick on 28 May 2017
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: