- give an example of inputs that give INCORRECT output, and explain why
Check whether values of a certain column of a matrix is between two values
5 ビュー (過去 30 日間)
古いコメントを表示
%{
I have a BUS matrix with 6 rows, column 12 is the max value and column 13 is the minimum value.
I want to check if column 8 values are between column 12 and 13 values.
Now, I know that the answer of volmax are all greater than 0 but some values of volmin are less than 0.
For some reason, my code display Yes which means that volmax and volmin are greater than or equal to zero.
But I know this is not true. My guess is that my code is comparing only the first row and it ignore the rest of the rows
Can you help me to figure this out?
}%
volmax= BUS(:,12)- BUS(:,8) % we are good if volmax >=0
volmin= BUS(:,8)- BUS(:,13) % we are good if volmin >=0
if volmax<0 | volmin <0
disp('NO')
else
disp('YES')
end
end
0 件のコメント
採用された回答
the cyclist
2021 年 11 月 30 日
OK, still trying to understand everything, but I think this does what you want:
% Sample input
BUS(:, 8) = [2;2;2];
BUS(:,12) = [3;3;3];
BUS(:,13) = [1;1;1];
volmax = BUS(:,12)- BUS(:,8); % we are good if volmax >=0
volmin = BUS(:,8)- BUS(:,13); % we are good if volmin >=0
if any((volmin<0)|(volmax<0))
disp('NO')
else
disp('YES')
end
Change the inputs around, and see if it is correct. If this is NOT correct, then please
その他の回答 (1 件)
the cyclist
2021 年 11 月 30 日
I think you intended
volmax<0 & volmin <0
rather than
volmax<0 | volmin <0
because you want to meet both conditions ("AND"), not just either condition ("OR").
Also, be aware that for vector input V, you will only enter the if statement
if V
...
end
if all elements of the vector V are true. (It is not some kind of implicit loop that works down the vector.)
Note that the expression
volmax<0 | volmin <0
(not using the if structure at all) will be a logical vector, with TRUE/FALSE entries corresponding to each row.
4 件のコメント
the cyclist
2021 年 11 月 30 日
I misunderstood your logic, and I see why you chose | now. Sorry for the confusion.
In your original code, it is not just checking the first element; it is checking whether ALL the elements of the vector meet the condition. Here is a simple example:
if [true true true]
disp('All elements are true')
else
disp('At least one element is false')
end
if [true false true]
disp('All elements are true')
else
disp('At least one element is false')
end
The reason your second code example works is that you are using a for loop, checking one value at a time (not trying to check the entire vector at once).
Question: Suppose 2 rows do not meet the condition, and 3 rows do. What do you want for output? Should the output be 5 "YES" / "NO" values (one per row), or do you just want a single "YES" / "NO", based on whether all rows are ok?
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!