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
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
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!