# How can I do such a "averageifs"(excel) process in Matlab?

12 views (last 30 days)
jee young yoo on 16 Aug 2019
Commented: jee young yoo on 16 Aug 2019
Hello,
How can I perform "sumifs" process in Matlab?
for example,
x1 = [ 201901, 201901, 201901, 201902, 201902, 201902, 201903, 201903, 201903], array, timetable
y1 = [1.52, 1.23, 1.42, 1.46, 2.42, 2.35, 3.24, 3.21, 3.44], array, double.
I'd like to do average [201901, 201902, 201903] and create new varaible with
x2 = [201901, 201902, 201903]
y2 = [x.xx, y.yy, z.zz]
? I've check some answers with accumarray function but it is still hard to understand.
Many thks.

Rik on 16 Aug 2019
Edited: Rik on 16 Aug 2019
Using accumarray is probably better, but you can also use the unique function and a for loop to find the sum and the count.
Edit:
I already gave you some pointers you could have tried. Everyone starts out by trying random things until it works. But the code below shows both methods.
x1 = [ 201901, 201901, 201901, 201902, 201902, 201902, 201903, 201903, 201903];
y1 = [1.52, 1.23, 1.42, 1.46, 2.42, 2.35, 3.24, 3.21, 3.44];
x_method_1=unique(x1);
y_method_1=zeros(size(x_method_1));
for n=1:numel(y_method_1)
%you could also find the count with sum(L) and the sum with sum(y1(L))
L=ismember(x1,x_method_1(n));
y_method_1(n)=mean(y1(L));
end
[x_method_2,~,ic] = unique(x1);
y_method_2=accumarray(ic,y1,[],@mean);
y_method_2=reshape(y_method_2,size(x_method_2));
%confirm the methods are equivalent
assert(max(abs(y_method_2-y_method_1))<2*eps)

jee young yoo on 16 Aug 2019
Yes, that maybe.. but the reason why I write question in detail is to know how to perform the command exactly, as I am a beginner in Matlab. Thanks for your time.
jee young yoo on 16 Aug 2019
I am working on this problem 4 hours now. But your solution helped..! Thanks! :)

R2019a

### Community Treasure Hunt

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

Start Hunting!

Translated by