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

3 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

MathReallyWorks
MathReallyWorks el 28 de Mayo de 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.
  3 comentarios
Stephen23
Stephen23 el 28 de Mayo de 2017
Editada: Stephen23 el 28 de Mayo de 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.

Iniciar sesión para comentar.

Más respuestas (1)

Stephen23
Stephen23 el 28 de Mayo de 2017
Editada: Stephen23 el 28 de Mayo de 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:
And also read these:
  1 comentario
MathReallyWorks
MathReallyWorks el 28 de Mayo de 2017
Hey Stephen,
Thanks for your feedback. I liked your answer. This is great. And thanks for those important links too.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by