Sean‘s pick this week is catstruct by Jos (10584).
Have you ever had two structures and wanted to combine them into one?
The above question is kind of ambiguous. Do you mean?
firststruct.x = pi secondstruct.x = exp(1) combinedstruct = [firststruct secondstruct]
firststruct = struct with fields: x: 3.1416 secondstruct = struct with fields: x: 2.7183 combinedstruct = 1×2 struct array with fields: x
thirdstruct.x = pi fourthstruct.y = exp(1) combinedstruct = [thirdstruct fourthstruct]
thirdstruct = struct with fields: x: 3.1416 fourthstruct = struct with fields: y: 2.7183 Error using horzcat
Names of fields in structure arrays being concatenated do not match. Concatenation of structure arrays requires that these arrays have the same set of fields.
Well if you wanted the first one you’re in luck. That worked because the structures have like fieldnames. If they don’t, you get the error in the second one. This is where catstruct comes to the rescue.
No not that cat-struct. This one!
combinedstruct = catstruct(thirdstruct, fourthstruct)
combinedstruct = struct with fields: x: 3.1416 y: 2.7183
I discovered catstruct while working with regular expressions to parse a custom text file. I used separate regular expressions and kept ending up with multiple structs. Catstruct made joining them into one really easy. Here’s a representative example:
str = "Hello World. 15 quick brown foxes jumped over 3 2.3ft tall lazy dogs"; % Extract pieces using regular expressions. foxes = regexp(str, '(?<foxes>\d+)(?=[\w\s]*fox)', 'names') dogs = regexp(str, '(?<=fox\D*)(?<dogs>\d+)', 'names') dogheight = regexp(str, '(?<dogheight>[\.\d]+)ft', 'names') heightunit = regexp(str, '\d(?<heightunit>[a-zA-Z]+)\s', 'names')
foxes = struct with fields: foxes: "15" dogs = struct with fields: dogs: "3" dogheight = struct with fields: dogheight: "2.3" heightunit = struct with fields: heightunit: "ft"
info = catstruct(foxes, dogs, dogheight, heightunit)
info = struct with fields: foxes: "15" dogs: "3" dogheight: "2.3" heightunit: "ft"
Give it a try and let us know what you think here or leave a comment for Jos.
Published with MATLAB® R2017a
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.