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

3 次查看(过去 30 天)
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
Rik 2019-8-16
编辑:Rik 2019-8-16
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)
  2 个评论
jee young yoo
jee young yoo 2019-8-16
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
jee young yoo 2019-8-16
I am working on this problem 4 hours now. But your solution helped..! Thanks! :)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by