我尝试提供一个函数来rowfun
返回与输入高度相同的多行输出。它似乎按预期工作。
% Example table with 2-column-array as a single data field
x = table( [1;1;2;2] , [[2;2;1;1] [2;1;2;1]] , ...
'VariableNames' , {'idx' 'Field2columns'} )
x = idx Field2columns
___ _____________
1 2 2
1 2 1
2 1 2
2 1 1
% Example anonymous function takes all rows with same idx value and
% reverse their row order
y = rowfun( @(z) z(end:-1:1,:) , x , 'Input','Field2columns' , ...
'Grouping','idx' , 'OutputVar','OutVar' )
y = idx GroupCount OutVar
___ __________ ______
1 1 2 2 1
1_1 1 2 2 2
2 2 2 1 1
2_1 2 2 1 2
% Append the generated data to original table
[ x y(:,{'OutVar'}) ]
ans = idx Field2columns OutVar
___ _____________ ______
1 1 2 2 2 1
1_1 1 2 1 2 2
2 2 1 2 1 1
2_1 2 1 1 1 2
这使得代码非常高效。否则我将不得不遍历 的所有不同值x.idx
,为每个值提取匹配的行x
,生成行反转子集并编译结果。
我唯一担心的是我假设匿名函数输出的行顺序将保持不变,并且每一行都将与 table 中的相应行对齐x
。例如,如果 idx=7,则 idx=7 的第 N 行将x
被附加到右侧,而匿名函数输出中的第 N 行应用于x(x.idx==7,:)
.
该rowfun
文档不处理第一个参数表示返回多行输出的函数的情况。我只有观察到的行为可以依赖。是否建议利用这种行为来简化我的代码,或者依赖这种未记录的行为是不好的做法,例如,可能不涵盖极端情况,并且 TMW 没有义务在未来保持当前行为?