Removing data from an array using subsets

Hello, I have a 1x200 matrix where I'd like to simply remove all 0's then use that data in a follow on equation. Below is a short example:
x = [0;0;0;0;1;1;1;0;1;1]
NewPoints = prod(x)
I believe if I can make a subset of x that removes all the 0's but am having trouble. Thanks for any help!

 Accepted Answer

Use logical indexing to identify and remove the zero-elements from x:
x = [0;0;0;0;1;1;1;0;1;1];
x(x == 0) = [];

2 Comments

Thank you, that worked!
Identifying candidates to remove is one way to solve this problem. Identifying candidates to keep is another.
x = [0; 0; 0; 0; 1; 1; 1; 0; 1; 1];
xRemove = x; % Make a copy of x so we can look at the original later
toRemove = x == 0;
xRemove(toRemove) = []
xRemove = 5×1
1 1 1 1 1
toKeep = x ~= 0;
xKeep = x(toKeep)
xKeep = 5×1
1 1 1 1 1
If you look at the elements of x and the two masks you can see that each element is selected by either toRemove or toKeep, not both and not neither.
showMasks = table(x, toRemove, toKeep)
showMasks = 10×3 table
x toRemove toKeep _ ________ ______ 0 true false 0 true false 0 true false 0 true false 1 false true 1 false true 1 false true 0 true false 1 false true 1 false true

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2021b

Tags

Community Treasure Hunt

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

Start Hunting!