0

我有一个 10 x 10 结构,有四个字段 a、b、c、d。

如何将此结构转换为 10 x 10 矩阵,其条目仅来自字段 a?

4

2 回答 2

1

您可以依赖str.a返回逗号分隔列表的事实。因此,我们可以将这些值连接在一起,并将结果数组重塑为与输入结构相同的大小。

% If a contains scalars
out = reshape([str.a], size(str));

% If a contains matrices
out = reshape({str.a}, size(str));
于 2016-12-04T13:47:26.623 回答
0

一种衬垫解决方案

res = cellfun(@(strctObj) strctObj.a,str,'UniformOutput',false);

进一步说明

定义一个提取 a 值的单行函数。

getAFunc = @(strctObj) strctObj.a;

使用 MATLAB 的 cellfun 函数将其应用于您的单元格并提取矩阵:

res = cellfun(@(strctObj) getAFunc ,strctCellObj,'UniformOutput',false);

例子

%initializes input
N=10;
str = cell(N,N);
for t=1:N*N
  str{t}.a = rand; 
  str{t}.b = rand; 
  str{t}.c = rand; 
  str{t}.d = rand; 
end
%extracts output matrix
res = cellfun(@(strctObj) strctObj.a,str,'UniformOutput',false);
于 2016-12-04T06:57:00.153 回答