comparison/checking without for loop

Hi there,
Say if I have a random event with just -1 and 1. e.g. a = randsrc(5,1);%that will generate a 5x1 matrix with just -1 or 1
Now say if I want to check how many of -1 or 1 in a, how can I do that without using for loop? I try to do this but doesn't work:
m =0;
if(a == 1)
m = m+1;
end
Any help would be really appreciated.
Cheers,
Rak

1 件のコメント

Andrei Bobrov
Andrei Bobrov 2012 年 5 月 4 日
accumarray((a > 0) + 1,a)

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

 採用された回答

Geoff
Geoff 2012 年 5 月 4 日

1 投票

nneg = sum(a==-1);
npos = sum(a==1);

5 件のコメント

Ricky
Ricky 2012 年 5 月 4 日
Thanks Geoff,
How about if I want to assign something to r if a is 1 and to r1 if a is -1?
Ricky
Ricky 2012 年 5 月 4 日
say I have t0 and t1
and I want to assign r = t0 if a is 1 and r = t1 if a is -1?
Geoff
Geoff 2012 年 5 月 4 日
r(a==-1) = 0;
r(a==1) = 42;
This is called logical indexing... You can do whatever you like. The following example selects out of a only positive values less than 20:
a(a<20 & mod(a,2)==0)
And if you want to assign something different for every selected value, just use an array (or matrix) the same size as the number of selected items:
r(a==-1) = rand(1,sum(a==-1));
Geoff
Geoff 2012 年 5 月 4 日
Yes... replace '0' and '42' in my example with 't1' and 't0' respectively.
Ricky
Ricky 2012 年 5 月 4 日
Thanks Geoff!!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

質問済み:

2012 年 5 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by