如何将由 int 32 和 double 组成的元胞数组更改为双精度矩阵?

How can I change a cell array consisting of int 32 and double to matrix of doubles?

我有一个结构,我想将其更改为矩阵。所以我得到了cell2mat(struct2cell(d))。但是 struct2cell(d) 给了我

6×1 cell array

{1100×1 int32 }
{1100×1 int32 }
{1100×1 int32 }
{1100×1 int32 }
{1100×1 double}
{1100×1 double}

cell2mat(struct2cell(d)) 给我错误:

All contents of the input cell array must be of the same data type.

所以我的问题是如何将它们全部转换为 double?或者我怎样才能最终得到一个矩阵?

您可以使用 cellfun 转换单元格的每个元素(这基本上是一个隐藏的 for 循环):

%Dummy data
s.a = int16([1:4])
s.b = linspace(0,1,4)

%struct -> mat
res = struct2cell(s);
res = cellfun(@double,res,'UniformOutput',0) %cast data type to double
res = cell2mat(res)

我们可以做一个简单的循环...

f = fieldnames( d );
nf = numel( f );
output = cell( nf, 1 );
for ii = 1:nf
    output{ii} = double( d.(f{ii}) );
end
output = [output{:}];

您可以在修改后的结构上使用structfun to loop over all fields in your structure and convert them to double first. Then you can use cell2mat and struct2cell。或者,您可以直接从 structfun 获取元胞数组,然后将这些元胞内容简单地连接到一个数组中:

>> s = struct('a', int32(1:10).', 'b', pi.*ones(10, 1));  % Sample data
>> mat = cell2mat(structfun(@(v) {double(v)}, s).');

mat =

   1.000000000000000   3.141592653589793
   2.000000000000000   3.141592653589793
   3.000000000000000   3.141592653589793
   4.000000000000000   3.141592653589793
   5.000000000000000   3.141592653589793
   6.000000000000000   3.141592653589793
   7.000000000000000   3.141592653589793
   8.000000000000000   3.141592653589793
   9.000000000000000   3.141592653589793
  10.000000000000000   3.141592653589793