Cha*_*had 10 matlab struct cell-array
这是为此问题创建示例单元数组的代码:
mycell = cell([5,1]);
for i = 1 : size(mycell)
mystruct = struct();
mycell{i} = mystruct;
mycell{i}.field1 = i;
end
Run Code Online (Sandbox Code Playgroud)
我期望mycell{:}.field1做我想做的事,但它给出了一个错误.我可以使用以下for循环:
for i = 1 : size(mycell)
mycell{i}.field1
end
Run Code Online (Sandbox Code Playgroud)
但我更喜欢更简单或更优雅的解决方案,因为想要将mycell.field1的所有元素用作绘图中的y变量.有任何想法吗?
Sha*_*hai 16
如果单元格数组中的所有结构都具有与您相同的字段:
mycell = [ mycell{:} ]; % convert cell array to struct array
y = [ mycell(:).filed1 ]; % get the values
Run Code Online (Sandbox Code Playgroud)
另一种方法使用 cellfun
y = cellfun( @(x) x.field1, mycell );
Run Code Online (Sandbox Code Playgroud)
假设所有mycell{ii}.filed1都是标量,否则你需要添加'UniformOutput', false到标量cellfun.
注意:如果某些字段为空([]),这些方法可能无法按预期工作.
一句小话:在Matlab中
使用i和j作为变量不是一个好习惯.