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

4 vues (au cours des 30 derniers jours)
jee young yoo
jee young yoo le 16 Août 2019
Commenté : jee young yoo le 16 Août 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.

Réponse acceptée

Rik
Rik le 16 Août 2019
Modifié(e) : Rik le 16 Août 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)
  2 commentaires
jee young yoo
jee young yoo le 16 Août 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
jee young yoo le 16 Août 2019
I am working on this problem 4 hours now. But your solution helped..! Thanks! :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by