|
"Peter Perkins" <Peter.Remove.Perkins.This@mathworks.com> wrote in message
news:j9h6vo$41c$1@newscl01ah.mathworks.com...
> On 11/10/2011 1:44 PM, pipa wrote:
>> fn(1).name = 1
>> fn(2).name = 2
>> fn(3).name = 3
>>
>> Now I want to store fn.name into another variable:
>>
>> var = fn.name; %var only stores 1
>> var = fn(:).name %var still stores 1
>> var = fn(1:3).name %var still stores 1
>
> Pipa, it is not so obvious, but what you need is
>
> var = [fn.name]; % creates a row
>
> or perhaps
>
> var = [fn.name]'; % creates a column
This will work for numeric values, but from the name of your struct's field
I suspect you're going to want to store char arrays (strings) in that field.
If so, square brackets may not be exactly what you want:
>> fn(1).name = 'Peter';
>> fn(2).name = 'Steve';
>> fn(3).name = 'ade77';
>> [fn.name]
ans =
PeterSteveade77
Instead, use curly braces to create a cell array, each cell of which
contains one string.
>> {fn.name}
ans =
'Peter' 'Steve' 'ade77'
>> but I want to avoid for loop as I have a huge data set.
>
> If that's true, then you might consider using something other than a
> structure array to begin with, if that's an option. You may be using a
> structure array because of the nice "named field indexing" that it
> provides. If you have access to the Statistics Toolbox, the dataset array
> has a similar syntax, and is often more convenient than a structure array
> for data where the values of one field across all elements of the array
> are the same type and size. In this case, all you'd need to do would be
>
> var = fn_ds.name;
>
> to get the vector of values, and often you don't even need to assign to a
> temporary variable because you can insert fn_s.name whereever you'd use
> var. Another benefit is that the storage of numeric values would require
> much less memory, because of the different ways that structure arrays and
> dataset arrays store data internally. "doc dataset" will get you started.
Even if you don't want to or can't use a dataset array, consider whether you
want to use an array of structs or a scalar struct each field of which is an
array. Which "slicing" orientation you choose depends on whether you want to
obtain all the information about one thing (a person's online dating profile
tells you a lot about that one person, but nothing about other people) or a
particular piece of information for all the things about which you have data
(a telephone book just includes phone numbers, and it includes [roughly]
everyone's phone number, but it doesn't tell you much else about them) more
frequently. In addition, the extra headers for each struct in the struct
array can add up after a while.
>> S1 = repmat(struct('a', 1), 1, 100);
>> S2 = struct('a', ones(1, 100));
>> whos S1 S2
Name Size Bytes Class Attributes
S1 1x100 12064 struct
S2 1x1 976 struct
--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com
|