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
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
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
추가 답변 (2개)
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] ;
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
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!