how to average column 3 when column 1 and column 2 satisfies some condition in matrix

조회 수: 1 (최근 30일)
i have a n*3 matrix as shown below
A B C
1 1 2
1 2 22
1 2 12
1 3 0
1 3 4
2 2 6
2 2 0
2 3 2
2 3 2
I need the result as
A B C
1 1 2
1 2 17 # average
1 3 4 #no need to average if value =0
2 2 6
2 3 2
  댓글 수: 1
Luna
Luna 2019년 1월 8일
What is the rule of the condition could you please explain?
And how it relates with the A and B columns?

댓글을 달려면 로그인하십시오.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 1월 8일
편집: Andrei Bobrov 2019년 1월 8일
T = readtable('file1.txt');
or
M = [1 2 22
1 2 12
1 3 0
1 3 4
2 2 6
2 2 0
2 3 2
2 3 2];
T = array2table(M,'v',{'A','B','C'});
solution:
out = varfun(@(x)sum(x)/nnz(x),T,'GroupingVariables',{'A','B'});

추가 답변 (2개)

KSSV
KSSV 2019년 1월 8일
A = [1 2 22
1 2 12
1 3 0
1 3 4
2 2 6
2 2 0
2 3 2
2 3 2];
[c,ia,ib] = unique(A(:,1:2),'rows') ;
iwant = c ;
m = zeros(length(c),1) ;
for i = 1:size(c,1)
T = A(ib==i,3) ;
if abs(min(T))>0
m(i) = mean(T) ;
end
end
iwant = [ iwant m] ;
  댓글 수: 1
anas ibnu
anas ibnu 2019년 1월 8일
편집: anas ibnu 2019년 1월 8일
i hope this will work on proper altration
now theproblem is, its not geting the required matrix of format n/2 *3

댓글을 달려면 로그인하십시오.


madhan ravi
madhan ravi 2019년 1월 8일
편집: madhan ravi 2019년 1월 8일
Note: Problem is unclear still. Are you sure about your desired result ? What's the condition ? How did you get 2 2 2 at the end ?
A=a(1:2:end,:);
B=a(2:2:end,:);
for i = 1:size(A,1)
if A(i,end) || B(i,end) ~= 0
B(i,end)=(A(i,end)+B(i,end))/2;
end
end
Result = B
Gives:
Result =
1 2 17
1 3 2 % (2+2)/2 = > 2 How did you get 4 , if you say average??
2 2 3
2 3 2
  댓글 수: 3
anas ibnu
anas ibnu 2019년 1월 8일
i am sorry the last line was wrong
this is my n*3 matrix
A B C
1 1 4
1 2 22
1 2 12
1 3 0
1 3 4
2 2 6
2 2 0
2 3 2
2 3 2
and i need answer as (n/2)*3 matrix1
A B C
1 1 4
1 2 (22+12)/2 # average
1 3 4 #no need to average if value =0
2 2 6
2 3 2

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Correlation and Convolution에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by