I have a code but am unable to use if conditions with matrix value
4 views (last 30 days)
Show older comments
My code required a condition for avoiding if 0 value read from text and continue to verify the next value
0 Comments
Answers (2)
Star Strider
on 5 Sep 2025
I cannot understand what you want help with.
If you want to avoid using values that equal 0, one way is to use 'logical indexing' to detect them --
data = randi([0 19], 10, 1)
Lv = data == 0
data_nonzero = data(~Lv)
Ypou can also use this in a matrix so that rows or columns will be deleted when a spacific row or column is equal to 0 (or any other value you choose).
.
2 Comments
Star Strider
on 9 Sep 2025
I still do not know what that is.
I may be able to provide more help if I understand what your problem actually is, and the question you are asking. If you do nt want to provide your actual data, example data is enough.
Steven Lord
on 9 Sep 2025
You haven't told us what you're doing or why Star Strider's suggestion didn't work for your application, so we can't offer specific suggestions for how to achieve your goal. But looking at your question literally: "...unable to use if conditions with matrix value" the documentation for the if keyword describes its behavior if the condition is non-scalar: "if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
So if you have a non-scalar value for your expression, as long as it's not empty and as long as no element is zero, the if statement will be satisfied and its body will execute.
if [1 2 3 4]
disp('satisfied')
else
disp('not satisfied')
end
If even one element of the expression is 0, the if statement will not be satisfied and its body will not execute. If that if statement has an else that will be executed instead.
if [1 2 0 4]
disp('satisfied')
else
disp('not satisfied')
end
And if the expression is empty, the if statement will not be satisfied.
if []
disp('satisfied')
else
disp('not satisfied')
end
0 Comments
See Also
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!