MATLAB Answers

How can I count how many numbers are different from '-1'?

2 ビュー (過去 30 日間)
Davide Conti
Davide Conti 2019 年 11 月 1 日
コメント済み: Walter Roberson 2019 年 11 月 5 日
Hi,
Example: Suppose we a have a matrix A
A= [1 -1 0 -1 0 0 -1 0 -1 -1 -1 -1 -1 -1 -1]
How can I count how many numbers are different from '-1'?

  2 件のコメント

Shubhashree Bal
Shubhashree Bal 2019 年 11 月 1 日
Search for how many negative number exists in A. than subtract that from length of array. Or Write a loop for how many positive number exists in array.
Code attached below:
Close all;
clear all;
A= [1 -1 0 -1 0 0 -1 0 -1 -1 -1 -1 -1 -1 -1];
count = 0;
for i = 1: length(A)
if(A(i)>=0)
count = count +1;
end
end
Davide Conti
Davide Conti 2019 年 11 月 5 日
Ok thanks, but if i wanted to do it for every line of my matrix?
For examples:
1 -1 0 -1 0 0 -1 0 -1
4 2 3 -1 0 3 1 2 -1
in this case for the first row the numbers different form '-1' are 5, in the second row they are 7.
With your loop it comes out that in the second row they are 12, because it considers the first row.

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

回答 (2 件)

Fangjun Jiang
Fangjun Jiang 2019 年 11 月 1 日
start with B=A~=-1

  1 件のコメント

Walter Roberson
Walter Roberson 2019 年 11 月 5 日
And then sum() along the appropriate axis.

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


Pedro Martinez
Pedro Martinez 2019 年 11 月 1 日
Total = sum (A==-1);

  1 件のコメント

Walter Roberson
Walter Roberson 2019 年 11 月 5 日
That gives the number of rows of -1 but the user wants the number of columns that are not -1

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

Community Treasure Hunt

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

Start Hunting!

Translated by