structfun output array not working

3 次查看(过去 30 天)
timelockdata.m0='timelock_m0';
timelockdata.m6='timelock_m6';
timelockdata.m3w='timelock_m3w';
timelockdata.m3b='timelock_m3b';
timelockdata.same='timelock_same';
timelockdata.diff='timelock_diff';
[m0,m6,m3w,m3b,same,diff]=structfun(@numel,timelockdata);
results in:
Error using numel
Too many output arguments.
How can I get the results of structfun to save in the name of the corresponding variables

回答(3 个)

Stalin Samuel
Stalin Samuel 2016-3-15
s=structfun(@numel,timelockdata,'UniformOutput',0)
  1 个评论
Hassan Aleem
Hassan Aleem 2016-3-15
This does not work. gives the same answer.It is a uniform output by the way.

请先登录,再进行评论。


Stephen23
Stephen23 2016-3-15
structfun is working fine. The problem is how you are using it. Try this:
vec = structfun(@numel,timelockdata);
  2 个评论
Hassan Aleem
Hassan Aleem 2016-3-15
this just puts the values into one variable named vec.
Stephen23
Stephen23 2016-3-16
编辑:Stephen23 2016-3-17
You have called structfun with numel, which only returns one output. The output is one variable. It does not magically become lots of separate variables as you seem to want. This is clearly explained in the structfun documentation. As I already said in my answer "The problem is how you are using it".
If you want vec allocated into multiple variables, then you have to do this yourself afterwards:
>> vec = 1:5
vec =
1 2 3 4 5
>> tmp = num2cell(vec);
>> [S.a,S.b,S.c,S.d,S.e] = tmp{:};
>> S
S =
a: 1
b: 2
c: 3
d: 4
e: 5
Personally I would keep them in one variable, because that makes data processing much simpler.

请先登录,再进行评论。


George Abrahams
George Abrahams 2022-12-30
Old question, but my fieldfun function on File Exchange / GitHub will process the fields of structure timelockdata and output a structure with the same fields.
timelockdata = struct('m0','timelock_m0','m6','timelock_m6','m3w',...
'timelock_m3w','m3b','timelock_m3b','same','timelock_same',...
'diff','timelock_diff');
fieldfun( @numel, timelockdata )
% ans = struct with fields:
% m0: 11
% m6: 11
% m3w: 12
% m3b: 12
% same: 13
% diff: 13
This is most likely superior to assigning the values to individual variables, which is exactly what you requested, as you don't need to hardcode the field names, so it will adjust if you change structure.
If you want to do that anyway, Stephen's answer essentially gave you the method: use Comma-Separated Lists.
timelocknumel = num2cell( structfun( @numel, timelockdata ) );
[ m0, m6, m3w, m3b, same, diff ] = timelocknumel{:}
% m0 = 11
% m6 = 11
% m3w = 12
% m3b = 12
% same = 13
% diff = 13

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by