I have 2 "if" conditions and i need to apply it to multiple rows of data.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Izza Ismail
am 28 Mai 2017
Kommentiert: MathReallyWorks
am 28 Mai 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.
0 Kommentare
Akzeptierte Antwort
MathReallyWorks
am 28 Mai 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 Kommentare
Weitere Antworten (1)
Stephen23
am 28 Mai 2017
Bearbeitet: Stephen23
am 28 Mai 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 Kommentar
MathReallyWorks
am 28 Mai 2017
Hey Stephen,
Thanks for your feedback. I liked your answer. This is great. And thanks for those important links too.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!