661
edits
Carandraug (talk | contribs) (→Retrieve a field value from all entries in a struct array: strcmpi for indexing) |
Carandraug (talk | contribs) (→Structures: use a less morbid example) |
||
Line 6: | Line 6: | ||
You have a struct array with multiple fields, and you want to acess the value from a specific field from all elements. For example, you want to return the age from all pacients in the following case: | You have a struct array with multiple fields, and you want to acess the value from a specific field from all elements. For example, you want to return the age from all pacients in the following case: | ||
samples = struct ("patient", {"Bob", "Kevin", "Bob" , "Andrew"}, | |||
"age", [ 45 , 52 , 45 , 23 ], | |||
"protein", {"H2B", "CDK2" , "CDK2", "Tip60" }, | |||
"tube" , [ 3 , 5 , 2 , 18 ] | |||
); | |||
==== Solution ==== | ==== Solution ==== | ||
Indexing the struct returns a comma separated list so use them to create a matrix. | Indexing the struct returns a comma separated list so use them to create a matrix. | ||
[ | [samples(:).age] | ||
This however does not keep the original structure of the data, instead returning all values in a single column. To fix this, use {{Codeline|reshape()}}. | This however does not keep the original structure of the data, instead returning all values in a single column. To fix this, use {{Codeline|reshape()}}. | ||
reshape ([ | reshape ([samples(:).age], size (samples)) | ||
==== Discussion ==== | ==== Discussion ==== | ||
Returning all values in a comma separated lists allows you to make anything out of them. If numbers are expected, create a matrix by enclosing them in square brackets. But if strings are to be expected, a cell array can also be easily generated with curly brackets | Returning all values in a comma separated lists allows you to make anything out of them. If numbers are expected, create a matrix by enclosing them in square brackets. But if strings are to be expected, a cell array can also be easily generated with curly brackets | ||
{ | {samples(:).name} | ||
You are also not limited to return all elements, you may use logical indexing from other fields to get values from the others: | You are also not limited to return all elements, you may use logical indexing from other fields to get values from the others: | ||
[ | [samples([samples(:).age] > 34).tube] ## return tube numbers from all samples from patients older than 34 | ||
[ | [samples(strcmp({samples(:).protein}, "CDK2").tube] ## return all tube numbers for protein CDK2 | ||
== Input/output == | == Input/output == |