Counting the occurrence of a value=Inf in an array

9 次查看(过去 30 天)
I am given a vector for instance
R=[1;2;3;4;5;6 Inf; 7; Inf];
Is there a function in matlab which has inputs R and Inf and gives me back the number of occurrence of Inf in R?

回答(1 个)

Paras Gupta
Paras Gupta 2022-7-6
Hi,
It is my understanding that you need a function to find the total number of 'Inf' values in a given array. Though there does not seem to be any one particular function to find the same, you can very easily find the solution using two functions as is illustrated in the following code.
R = [1; 2; 3; 4; 5; 6; Inf; 7; Inf];
% isinf returns a logical array with true (1) at indices where element is inf
% nnz returns the number of non-zero values in the array
infCount1 = nnz(isinf(R))
infCount1 = 2
% one could also use sum function instead of nnz
infCount2 = sum(isinf(R))
infCount2 = 2
You can refer to the following documentations on isinf, nnz, and sum for more information on how the above code works.
Hope it helps!
  1 个评论
Steven Lord
Steven Lord 2022-7-6
isinf may or may not be the right tool, depending on whether the user wants all infinite values in the array to be counted or just the positive ones.
% Sample data: Inf for multiples of 3, -Inf for multiples of 5, NaN for both
x = (1:15).';
x(3:3:end) = Inf;
x(5:5:end) = -Inf;
x(15) = NaN;
allInf = isinf(x);
justPositive = x == Inf;
nonfinites = ~isfinite(x);
results = table(x, allInf, justPositive, nonfinites)
results = 15×4 table
x allInf justPositive nonfinites ____ ______ ____________ __________ 1 false false false 2 false false false Inf true true true 4 false false false -Inf true false true Inf true true true 7 false false false 8 false false false Inf true true true -Inf true false true 11 false false false Inf true true true 13 false false false 14 false false false NaN false false true

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by