Finding how mych values contain a specific number in a matrix

2 ビュー (過去 30 日間)
Lola Rapoport
Lola Rapoport 2018 年 4 月 20 日
コメント済み: Walter Roberson 2018 年 4 月 20 日
I built the next matrix:
A=rand(100, 100)
I need to find how much values contain '3' in the first four digits. I would like to know how to do that.

採用された回答

Walter Roberson
Walter Roberson 2018 年 4 月 20 日
 nnz(cellfun(@(S) ismember('3',S), sprintfc('%4d',floor(A*10000)))) 
  2 件のコメント
Walter Roberson
Walter Roberson 2018 年 4 月 20 日
The '%4d' could be just '%d' here.
But if you were searching for 0's then you should use '%04d'
Walter Roberson
Walter Roberson 2018 年 4 月 20 日
 B14 = floor(A*10000);
 D4 = mod(B14, 10);
 B13 = (B14-D4)/10;
 D3 = mod(B13, 10);
 B12 = (B13-D3)/10;
 D2 = mod(B12, 10);
 D1 = (B12-D2)/10;
 nnz( any([D1(:), D2(:), D3(:), D4(:)] == 3, 2) )

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

その他の回答 (1 件)

David Fletcher
David Fletcher 2018 年 4 月 20 日
編集済み: David Fletcher 2018 年 4 月 20 日

Whilst I can admire the brevity of Walter's code, I might be inclined to use a more 'conventional' alternative

A=rand(100, 100);
extract=A;
count=0;
for iter=1:4
    %Prepare integer value for examination
    extract=extract*10;
    %remove fractional part
    intVals=floor(extract);
    %running total of '3's in each column
    count=count+sum(intVals==3);
    %subtract integer portion ready for next loop
    extract=extract-intVals;
    %Remove numbers where 3 has been found
    extract(intVals==3)=0;
end
total=sum(count); 

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by