此语句中的 MATLAB 错误 "scalar structure required for this assignment" 指的是什么?
What does the MATLAB error "scalar structure required for this assignment" refer to in this statement?
我有一个结构 space_averaged_data
,它有一个成员 Ps
,它被定义为一个长度可变的元胞数组。我在创建结构后为这个元胞数组赋值,如下所示(为清楚起见,我省略了其他结构字段):
Ps = cell( 1, num_p );
for p = 1:length(Ps)
Ps{p} = rand( 150, 1000 );
end
space_averaged_data = struct( 'Ps', cell( 1, length(Ps) ) );
for p = 1:length(Ps)
space_averaged_data.Ps{p} = mean( Ps{p}, 2 );
end
如果 num_p
的值为 1(即元胞数组不是数组),则一切正常。但是,如果 num_p
的值大于 1,则会出现以下错误:
Scalar structure required for this assignment.
Error in:
space_averaged_data.Ps{p} = mean( Ps{p}, 2 );
这个赋值中的非标量结构是什么?我不知道错误指的是什么。
您正在创建一个 1x5
struct
数组。引用 struct
documentation:
If value
is a cell array, then s
is a structure array with the same dimensions as value
. Each element of s
contains the corresponding element of value
.
由于表达式 struct( 'Ps', cell( 1, length(Ps) ) )
中的第二个参数是 1x5
cell
,输出 struct
将是 1x5
struct
数组,for
循环中的正确赋值将是
space_averaged_data(p).Ps = mean( Ps{p}, 2 );
要获得您想要的行为,请将第二个参数包装在 {}
中,使其成为 1x1
cell
数组:
space_averaged_data = struct( 'Ps', {cell( 1, length(Ps) )} );
和 for
循环应该按预期工作。
我有一个结构 space_averaged_data
,它有一个成员 Ps
,它被定义为一个长度可变的元胞数组。我在创建结构后为这个元胞数组赋值,如下所示(为清楚起见,我省略了其他结构字段):
Ps = cell( 1, num_p );
for p = 1:length(Ps)
Ps{p} = rand( 150, 1000 );
end
space_averaged_data = struct( 'Ps', cell( 1, length(Ps) ) );
for p = 1:length(Ps)
space_averaged_data.Ps{p} = mean( Ps{p}, 2 );
end
如果 num_p
的值为 1(即元胞数组不是数组),则一切正常。但是,如果 num_p
的值大于 1,则会出现以下错误:
Scalar structure required for this assignment.
Error in:
space_averaged_data.Ps{p} = mean( Ps{p}, 2 );
这个赋值中的非标量结构是什么?我不知道错误指的是什么。
您正在创建一个 1x5
struct
数组。引用 struct
documentation:
If
value
is a cell array, thens
is a structure array with the same dimensions asvalue
. Each element ofs
contains the corresponding element ofvalue
.
由于表达式 struct( 'Ps', cell( 1, length(Ps) ) )
中的第二个参数是 1x5
cell
,输出 struct
将是 1x5
struct
数组,for
循环中的正确赋值将是
space_averaged_data(p).Ps = mean( Ps{p}, 2 );
要获得您想要的行为,请将第二个参数包装在 {}
中,使其成为 1x1
cell
数组:
space_averaged_data = struct( 'Ps', {cell( 1, length(Ps) )} );
和 for
循环应该按预期工作。