Effacer les filtres
Effacer les filtres

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 vue (au cours des 30 derniers jours)

Réponse acceptée

Walter Roberson
Walter Roberson le 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 commentaires
Walter Roberson
Walter Roberson le 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.
sam
sam le 15 Sep 2022
Hi Walter, That's great. It worked fine. Thank you so much.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by