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

3 ビュー (過去 30 日間)
Izza Ismail
Izza Ismail 2017 年 5 月 28 日
コメント済み: MathReallyWorks 2017 年 5 月 28 日
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 件のコメント
MathReallyWorks
MathReallyWorks 2017 年 5 月 28 日
for i=1:length(D)
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by