looking up entire matrix for if then loop

2 ビュー (過去 30 日間)
Daniel Lee
Daniel Lee 2020 年 11 月 3 日
コメント済み: Daniel Lee 2020 年 11 月 3 日
Given A=[1 2 3 4 5 ]
  • I want to see when A > 1 and count how many times that was true (output should be 4 times)
  • I want to see when A > 2 and count how many times that was true (output should be 3 times)
  • I want to see when A > 3 and count how many times that was true (output should be 2 times)
  • I want to see when A > 4 and count how many times that was true (output should be 1 time)
  • I want to see when A > 5 and count how many times that was true (output should be 0 time)
I tried using below approach, but it does not output what I intended. I think it is only looking at one cell at a time.
is there a way to look entire matrix and get the count?
clear
n=5;
count=0;
r=exprnd(5,1,n);
for x=1:n
if r > x
count=count+1;
a(x)=count; %record output
else
count=count;
a(x)=count; %record output
end
end

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 11 月 3 日
Here is a loop-free simpler way
n=5;
count=0;
r=exprnd(5,1,n);
a = sum(r(:) > (1:n))
Result
>> r
r =
1.3006 15.7725 4.8618 1.7525 1.5769
>> a
a =
5 2 2 2 1
  2 件のコメント
Daniel Lee
Daniel Lee 2020 年 11 月 3 日
wowwwww never even knew that was possible... thanks bunch
Ameer Hamza
Ameer Hamza 2020 年 11 月 3 日
Yes, a very powerful aspect of MATLAB is vectorization, which makes the implementation of mathematical operations much simpler.
I am glad to be of help!

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

その他の回答 (1 件)

Mathieu NOE
Mathieu NOE 2020 年 11 月 3 日
hello
why not simply do that (example for when A > 1 and count how many times that was true (output should be 4 times)
A=[1 2 3 4 5 ];
k = find(A>1);
count = length(k);
  1 件のコメント
Daniel Lee
Daniel Lee 2020 年 11 月 3 日
Mathieu, thanks for the response as well-- I didnt know about find command. Will use it next time!

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

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by