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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
回答2:
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