How to write this below IF condition in MATLAB
1 次查看(过去 30 天)
显示 更早的评论
Let I have dataset with 4 variable = c1, c2, c3, c4 from 3 observations. I want to make a conclusion in this 3 observation based on the "IF" condition (I wrote this IF condition in excel):
=IF(AND(C1>C2,C1>C3,C1>C4),1,IF(AND(C2>C1,C2>C3,C2>C4),2,IF(AND(C3>C1,C3>C2,C3>C4),3,4)))
c1 c2 c3 c4 conclusion
0.05000 0.77426 0.07760 0.39404 ?
0.99888 0.32245 0.00001 0.00003 ?
0.99999 0.00000 0.00110 0.00000 ?
Note: in matlab there is no c1,c2,c3,c4 but column: 1,2,3,4
Can some one help me, how to write the code of this problem in matlab? many thanks!
0 个评论
采纳的回答
Image Analyst
2014-10-24
So what exactly do you have? I don't know if you have an array or a table. To get c1,c2,c3, and c4 from a table you do
c1 = t.c1;
c2 = t.c2;
c3 = t.c3;
c4 = t.c4;
To get c1,c2,c3, and c4 from an array you do
c1 = c(:, 1);
c2 = c(:, 2);
c3 = c(:, 3);
c4 = c(:, 4);
Then to do
IF(AND(C1>C2,C1>C3,C1>C4),1,IF(AND(C2>C1,C2>C3,C2>C4),2,IF(AND(C3>C1,C3>C2,C3>C4),3,4)))
you need to specify whether you want that done on a row by row basis , or if all elements (all rows) in something like C1>C2 need to be true. Which is it?
3 个评论
Image Analyst
2014-10-24
Try this:
[rows, columns] = size(c)
result = zeros(rows, 1);
for row = 1 : rows
c1 = c(row, 1);
c2 = c(row, 2);
c3 = c(row, 3);
c4 = c(row, 4);
if c1 > c2 && c1 > c3 && c1 > c4
result(row) = 1;
elseif c2 > c1 && c2 > c3 && c2 > c4
result(row) = 2
elseif c3 > c2 && c3 > c4
result(row) = 3;
else
result(row) = 4;
end
end
It looks like you could simply use max() and take the second return argument to get all this instead of doing this 4-way if statement, right?
for row = 1 : rows
[maxValue, indexOfMax] = max(c(row, :));
result(row) = indexOfMax;
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!