I have a code but am unable to use if conditions with matrix value

4 views (last 30 days)
My code required a condition for avoiding if 0 value read from text and continue to verify the next value

Answers (2)

Star Strider
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)
data = 10×1
18 14 0 6 0 14 15 13 12 15
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Lv = data == 0
Lv = 10×1 logical array
0 0 1 0 1 0 0 0 0 0
data_nonzero = data(~Lv)
data_nonzero = 8×1
18 14 6 14 15 13 12 15
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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
G Suresh
G Suresh on 9 Sep 2025
Thank You for you are respond. I agree that you are answer validated and limited to the specific solution.
But, My requirement is specific to our application.
Star Strider
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.

Sign in to comment.


Steven Lord
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
satisfied
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
not satisfied
And if the expression is empty, the if statement will not be satisfied.
if []
disp('satisfied')
else
disp('not satisfied')
end
not satisfied

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!