how to apply condition on multiple columns?

19 ビュー (過去 30 日間)
Mahrukh Farooq
Mahrukh Farooq 2017 年 3 月 30 日
編集済み: Stephen23 2017 年 3 月 31 日
I have a large data set that is unequal in every way so to get things done i have to apply condition on the element of the specific columns. E.g
1 1 234
1 1 234
1 1 180
1 2 345
1 2 674
.
.
.
8 1 453
8 1 678
8 2 478
8 2 345
8 2 345
.
.
.
31 21 456
31 22 452
31 22 345
31 23 670
31 23 567
31 23 456
what i want the programme to do is that check the value in column 1 if it equals 1 the check the value in column 2 if it equals 1 then take the mean of all the values in column 3 corresponding to column 2. similarly i want it to repeat for all the values in column 2 for 1st then all the other numbers in column 1 till last number in this case which is 31.
  1 件のコメント
Stephen23
Stephen23 2017 年 3 月 31 日
編集済み: Stephen23 2017 年 3 月 31 日
See my answer for a neater and more efficient solution than the accepted answer.

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

採用された回答

KSSV
KSSV 2017 年 3 月 31 日
A = [1 1 234
1 1 234
1 1 180
1 2 345
1 2 674
8 1 453
8 1 678
8 2 478
8 2 345
8 2 345
31 21 456
31 22 452
31 22 345
31 23 670
31 23 567
31 23 456] ;
B = [1 1] ;
[idx,val] = ismember(A(:,1:2),B,'rows') ;
% get mean
iwant = sum(A(idx,3))/nnz(idx)
  2 件のコメント
Mahrukh Farooq
Mahrukh Farooq 2017 年 3 月 31 日
It worked WOW! i just had to put it in a loop.
for i=1:31;
for ii=1:24;
B = [i ii] ;
[idx,val] = ismember(te(:,2:3),B,'rows') ;
% get mean
iwant(i,ii)= sum(te(idx,5))/nnz(idx);
end
end
Thanks a lot.GOD bless you.
"No one is useless in this world who lightens the burdens of the others"
~Charles Dickens.
Stephen23
Stephen23 2017 年 3 月 31 日
See my answer for neater and more efficient solution without the inefficient loops and multiple ismember calls.

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

その他の回答 (1 件)

Stephen23
Stephen23 2017 年 3 月 31 日
編集済み: Stephen23 2017 年 3 月 31 日
This can be done very efficiently with just one call to accumarray, no ugly loops are required:
>> out = accumarray(A(:,1:2),A(:,3),[],@mean);
And checking:
>> out(1,2) % mean when A(:,1)==1 & A(:,2)==2
ans = 509.50
>> out(8,1) % mean when A(:,1)==8 & A(:,2)==1
ans = 565.50

カテゴリ

Help Center および File ExchangeSimulink についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by