How can I remove rows with only zeros if the first column has the row names?

1 回表示 (過去 30 日間)
Georgina Wong
Georgina Wong 2019 年 12 月 15 日
コメント済み: Bhaskar R 2019 年 12 月 15 日
Can someone please tell me how I can remove the rows that contains only zeros when the first column has the row names? I have tried using the code below found on another Q&A, but it comes back with an error saying 'Error using any. Invalid data type. First argument must be numeric or logical'.
a =
glucose 7 2 5
sucrose 0 0 0
amylose 2 3 0
fructose 4 5 0
cellulose 0 0 0
galactose 2 0 1
b = a(any(a,2),:);
% What I would like b to look like:
b =
glucose 7 2 5
amylose 2 3 0
fructose 4 5 0
galactose 2 0 1

採用された回答

Bhaskar R
Bhaskar R 2019 年 12 月 15 日
You can do this in table/cell data type of variable a here i am taking table data type
Your variable a in table initialization as
% initialize your data
Names = {'glucose';'sucrose';'amylose'; 'fructose';'cellulose'; 'galactose'};
col1 = [7;0;2;4;0;2];
col2 = [2;0;3;5;0;0];
col3 = [5;0;0;0;0;1];
a = table(Names, col1, col2, col3, 'VariableNames', {'Names' 'col1' 'col2' 'col3'})
Now your data displays as table format as
a =
Names col1 col2 col3
___________ ____ ____ ____
'glucose' 7 2 5
'sucrose' 0 0 0
'amylose' 2 3 0
'fructose' 4 5 0
'cellulose' 0 0 0
'galactose' 2 0 1
Now remove the rows those all values are 0s
ind = find(~all(a{1:end, {'col1','col2', 'col3'}}==0, 2)); % index values of the all 0s rows
b = a(ind, :); % your required result
  2 件のコメント
Georgina Wong
Georgina Wong 2019 年 12 月 15 日
Thank you so much for your reply!
Bhaskar R
Bhaskar R 2019 年 12 月 15 日
It's my pleasure !! Cheers

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB Compiler についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by