Strange behaviour: struct with cell values

3 ビュー (過去 30 日間)
Simon Baeuerle
Simon Baeuerle 2022 年 6 月 27 日
コメント済み: Simon Baeuerle 2022 年 6 月 27 日
Hi there,
I'm writing a bigger piece of code and I am using structs as input variables. Now I changed (or tried to change) one input parameter in this struct from an array to cell. A little bit of code first:
order = 1; %Dumm
param = {1,2,zeros(2,2)};
opt1.order = order;
opt1.param = param;
opt2 = struct('order',order,'param',param);
As we can see from that bit of sample code,:opt1 is a 1x1 struct (which is what I want) and opt2 is a 1x3 struct (which I do ABSOLUTELY not want).
Why do the two lines of code behave differently?
Is there a way, that opt2 does not get expanded to a 1x3 struct?
Thanks so much!

採用された回答

Stephen23
Stephen23 2022 年 6 月 27 日
編集済み: Stephen23 2022 年 6 月 27 日
"Strange behaviour: struct with cell values"
The STRUCT() documentation explains what happens with cell array inputs: "... if value is a scalar cell array, then s is a scalar structure... If value is a nonscalar cell array, then s is a structure array with the same dimensions as value."
So it is very simple: if you want the output to be a scalar structure, then the input must be a scalar cell array.
You can achieve this very easily by nesting your (non-scalar) cell array in a scalar cell array:
order = 1; %Dumm
param = {1,2,zeros(2,2)};
opt2 = struct('order',order,'param',{param})
opt2 = struct with fields:
order: 1 param: {[1] [2] [2×2 double]}
  3 件のコメント
Steven Lord
Steven Lord 2022 年 6 月 27 日
The command opt1.param = param doesn't call the struct function. It performs indexed assignment. Indexed assignment into a struct array doesn't have the same behavior as calling the struct function.
Why does struct behave this way? That predates the start of my time at MathWorks, and I haven't done the archaeology to try to determine the reason for that behavior.
Simon Baeuerle
Simon Baeuerle 2022 年 6 月 27 日
Ok perfect. I'll just write a wrapper-function to ensure user-independent, predictable input in the struct and then I'm fine. Perfect! Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by