Hi, I have the following matlab structure. I want to apply zero padding according to maximum length (77). Could you kindly help? Thank you

1 回表示 (過去 30 日間)

採用された回答

Walter Roberson
Walter Roberson 2022 年 9 月 15 日
lengths = structfun(@length,YourStructure);
maxlen = max(lengths);
paddedStructure = structfun(@(S) [S;zeros(maxlen-size(S,1))], YourStructure, 'uniform', 0);
Note that when you use structfun() with UniformOutput not specified, or UniformOutput true (1), then it expects a scalar output and builds an array with one element for each field in YourStructure.
But when you use structfun() with UniformOutput false (0), then it builds an output structure with the same field names as YourStructure, in which each field is assigned the output of the function applied to the content of the structure. (The function does not get told what the field name is.)
  3 件のコメント
Walter Roberson
Walter Roberson 2022 年 9 月 15 日
Ah, I was misreading the diagram, thinking you had a scalar structure with multiple different fields. Your situation is different. Let me see:
ap_cell = struct2cell(ap_structure);
maxlen = max(cellfun(@length, ap_cell(:)));
ap_cell = cellfun(@(S) [S;zeros(maxlen-size(S,1),size(S,2))], ap_cell, 'uniform', 0);
ap_padded = cell2struct(ap_cell, fieldnames(ap_structure));
This will work even if the structure has multiple fields.
However, it might not do exactly what you want if the arrays inside the structure are not column vectors. It will always pad out by rows even if the inputs are row vectors. If the arrays inside the structure happen to be 2D with more columns than rows, then "length" will be detected as the number of columns (length is largest dimension). The code will fail if the arrays inside the structure have 3 or more dimensions.
sam
sam 2022 年 9 月 15 日
Hi Walter, That's great. It worked fine. Thank you so much.

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

その他の回答 (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