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!

 採用された回答

Voss
Voss 2021 年 12 月 5 日

0 投票

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 件のコメント

Daniel McDonald
Daniel McDonald 2021 年 12 月 5 日
Thank you, that worked!
Steven Lord
Steven Lord 2021 年 12 月 5 日
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

製品

リリース

R2021b

タグ

質問済み:

2021 年 12 月 5 日

コメント済み:

2021 年 12 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by