简体   繁体   中英

Matlab: Question regarding dataset()

I have around 50 elements (1 column char array) in my workspace. Is there any way to put all these elements into a single dataset without addressing each one explicitly. I have a variable x, which lists all the element names. I've already tried lots of things but nothing seems to work. The help for dataset() is also not helpful in this case. Hopefully somebody can help me with this final obstacle before I may finally see some results.

If I understand correctly, you have 50 variables in your workspace, all the names of which are stored in a variable x (which I presume is a 50-element cell array). The following example (with just 3 variables) illustrates how to get a set of variables into one dataset :

>> var1 = ['a'; 'b'; 'c'];        %# A 3-by-1 character array
>> var2 = ['d'; 'e'; 'f'];        %# A 3-by-1 character array
>> var3 = ['g'; 'h'; 'i'];        %# A 3-by-1 character array
>> x = {'var1'; 'var2'; 'var3'};  %# The variable names in a 3-by-1 cell array
>> varData = cellfun(@eval,x,'UniformOutput',false)  %# Collect the variable data
                                                     %#   in a cell array
>> data = num2cell([varData x],2);  %# Combine the variable data with the
                                    %#   variable names and collect each pair
                                    %#   in an additional cell array
>> ds = dataset(data{:})  %# Pass the data to dataset as a comma separated list

ds = 

    var1    var2    var3
    a       d       g   
    b       e       h   
    c       f       i   

Here's an example that shows how to label all your elements with a single name.

elems={'abc';'def';'ghi'};
d=dataset({elems,'NAME'})

d = 

    NAME     
    'abc'    
    'def'    
    'ghi' 

If you want to assign a different label (stored as a cell array) to each of the elements, then here's an example that shows how:

elems={'abc';'def';'ghi'};
names={'NAME1';'NAME2';'NAME3'};
data=cellfun(@(x){elems{x},names{x}},num2cell(1:length(elems)),'UniformOutput',false);
d=dataset(data{:})

d = 

    NAME1    NAME2    NAME3
    abc      def      ghi  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM