I need your help in solving the following problem. Column1 shows a grouping by integer. Any non-nan value in 开发者_高级运维Col2 should be inserted in the matrix for matching groupnumber(Col1).
mat = [ ...
1 nan
1 0.1
1 nan
1 nan
2 nan
2 nan
2 nan
3 0.5
4 nan
4 nan
4 nan
5 0.2
5 nan ] ;
ans = [ ...
1 0.1
1 0.1
1 0.1
1 0.1
2 nan
2 nan
2 nan
3 0.5
4 nan
4 nan
4 nan
5 0.2
5 0.2 ] ;
Please recommend a vectorized approach. Data is huge and is already being run in a for-loop. There will never be multiple non-nan values(col2) within a group (in mat). Thanks!
A solution using ACCUMARRAY will accomplish your goal:
values = accumarray(mat(:,1),mat(:,2),[],@min);
mat(:,2) = values(mat(:,1));
I use the function MIN here for convenience, since it will return the non-NaN
value if there is one, or NaN
if that's all there is. It's simpler than the logic involved in checking for any non-NaN
values using, say, the function ISNAN. You could actually use the function MAX as well, since it behaves the same way in this case.
精彩评论