How do I average values in a vector that share a common value in another vector?

I have two vectors: vector ID, which is an identifier of values and vector Measurements which contains values. I need to average all values that share the same identifier, not all of them share the same number of ID values. For example, the first three IDs are the same, therefore the first three values in Measurements must be averaged and put into a new vector called Output. Then, next 6 IDs are the same, so average those and put in the Output. So on and so forth. It is a research dataset where each patient has an ID and corresponding measurements, but not all them had the same number of measurements.

 Accepted Answer

splitapply(@mean, Meas, findgroups(ID))

3 Comments

Absolutely stunning solution. Thank you very much!
How to do this with their respective IDs attached to them?
Also, what if instead of the mean we want to find the difference between the largest and smallest values in that group with the same ID?

Sign in to comment.

More Answers (0)

Products

Release

R2022a

Asked:

on 14 Nov 2022

Commented:

on 14 Nov 2022

Community Treasure Hunt

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

Start Hunting!