如何将结构转换为矩阵
How to convert a struct to a matrix
我有一个 10 x 10 的结构,其中包含四个字段 a、b、c、d。
如何将此结构转换为 10 x 10 矩阵,其中的条目仅来自字段 a?
一个衬垫溶液
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);
您可以相信 str.a
returns 一个 comma-separated list。因此,我们可以将值连接在一起并将结果数组重新整形为与输入结构相同的大小。
% If a contains scalars
out = reshape([str.a], size(str));
% If a contains matrices
out = reshape({str.a}, size(str));
我有一个 10 x 10 的结构,其中包含四个字段 a、b、c、d。
如何将此结构转换为 10 x 10 矩阵,其中的条目仅来自字段 a?
一个衬垫溶液
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);
您可以相信 str.a
returns 一个 comma-separated list。因此,我们可以将值连接在一起并将结果数组重新整形为与输入结构相同的大小。
% If a contains scalars
out = reshape([str.a], size(str));
% If a contains matrices
out = reshape({str.a}, size(str));