Hi, I have the following matlab structure. I want to apply zero padding according to maximum length (77). Could you kindly help? Thank you
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Akzeptierte Antwort
Walter Roberson
am 15 Sep. 2022
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 Kommentare
Walter Roberson
am 15 Sep. 2022
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!