extract numbers form a column
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have a double collumn set of data, something like that:
Q= [0 15
0 18
0 12
1 12
2 15
0 17
0 12
2 7
0 12
0 11]
I need to get the mean values of ech array in column 2, where are zeros in column 1. Or at lest extract those aarays onto different variables, they need to be separated. Can anybody help me please?
Thank you
3 Kommentare
Akzeptierte Antwort
dpb
am 17 Jan. 2021
Bearbeitet: dpb
am 17 Jan. 2021
v=sprintf('%d',double([nan;Q(:,1);nan].'==0));
iStrt=strfind(v,'01').';
iEnd=[strfind(v,'10')-1].';
grpsums=arrayfun(@(i1,i2)sum(Q(i1:i2,2)),iStrt,iEnd).';
This is same idea except uses the string form to find the transitions from '01' or '10' in the vector. It first converts the numeric values to logical of T|F on zero to make the comparison an exact transition.
If use the arrayfun solution, remember that the anonymous function encapsulates the data of any variables not passed as arguments in the function and that those are NOT updated if the variable changes. Hence, if Q changes, executing the function above with just a new set of start,stop indices would still be summing over those positions in the old Q. Of course, when the whole line is executed, the anonymous function is redefined with the Q at the time; the above really only "bites" if you define the anonymous function as a function handle and then reuse that handle.
As noted, still seems to me ought to be an easy way to build a group subs index by section and then use accumarray directly, but how to increment the groups more efficiently than again using the above indices just never came to me...
6 Kommentare
dpb
am 18 Jan. 2021
Oh, yeah, I dunno how I got 'sum'; I do see it was mean that was requested.
If you want multiple statistics, you can optimize a little by writing a function that returns multiple outputs instead of using the anonymous function with the cost of having to write the function itself.
Alternatively, if you have the Statistics TB, you could use the grpstats function with a nul set ("[]") for the grouping variable and the list of desired statistics wanted; TMW has written the function in the additional toolbox.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!