Extract values from one field of structure, write into array
273 views (last 30 days)
Show older comments
I have a 25x1 structure (MyStruct) with 6 fields and I need an array with all 25 values from the first field ('name'). I tried different suggestions that I found in the forum but nothing seems to work for my case. I'm out of ideas but this seems like there should be a very simple solution... Here are some things I tried, I would really appreciate any tip!
MyStruct.name gives me all values but I didn't manage to write these into an array (without a loop),
MyArray = MyStruct.name
just writes the first value instead of all,
MyArray(:,1) = MyStruct.name
causes the error "Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-42."
MyArray = cell2mat({MyStruct(1:25).name})
creates a 1x25 cell which is then transformed into one single string concatenating all 25 values. I could probably split this string but I'd like a more elegant solution because there is no clear delimeter for splitting.
MyArray1 = {MyStruct(1:25).name}
MyArray2 = cellfun(@str2double,MyArray1)
just gives me 25 NaNs.
MyArray = getfield(MyStruct,'name')
again just yields the first field.
0 Comments
Answers (1)
Jan
on 2 Jun 2022
Edited: Jan
on 2 Jun 2022
Why do you call str2double? What is the contents of the 'name' fields? What is the wanted output? Mentioning the type of inputs and wanted outputs would be really useful to answer the question.
I guess:
MyArray1 = {MyStruct(1:25).name}
% Or shorter:
MyArray1 = {MyStruct(:).name}
% Even shorter:
MyArray1 = {MyStruct.name}
So this was almost correct:
MyArray = cell2mat({MyStruct(1:25).name})
just omit the cell2mat.
3 Comments
Jan
on 2 Jun 2022
You still did not explain clearly, what kind of array you need as output. The less the readers have to guess, the faster you get a useful answer.
'subject50001_01' does not look like a string, because strings use double quotes. The single quotes show, that the data are CHAR vectors.
Combining CHAR vectors to an array would create a CHAR matrix, which is a bad idea due to the padding. Therefore "cell strings" (which are not strings!) are preferred as arrays containing CHAR vcectors. Rmember, that "cell" is the short name for a "cell array", so even the cell string is an array.
If you want a string array (here the type string is meant!), use the command Walter has suggested - maybe with out the "(1:25)".
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!