How to extract table data using function variable?
1 view (last 30 days)
Show older comments
I have a function pulling data from tables stored in a cell array, and it depends on which column's data I want. In this case, the two variables are 'Dose' and 'Volume'.
Instead of indexing by '.VariableName' in two functions, I can use only one function with a switch block to extract data using parenthetical integers.
How do I extract data directly using the VarN (VariableName) string directly as the index variable name? MATLAB objects that the string variable is not the table variable:
>> newvoldata{5}.test{1}(1:2,:)
Unrecognized variable name 'test'.
>> test{1}
ans =
'Dose'
Here is the function I'm looking to simplify by removing the switch block and changing the table indexing method:
function output = GetDataFromEachCell(cellarray,string,VarN)
% decide which variable to pull
switch VarN
case 'dose'
VarInt = 4;
case 'vol'
VarInt = 5;
otherwise
error('Specify either ''dose'' or ''vol''!')
end
% count the number of cell elements
counter = 0;
for loop = 1:length(cellarray)
counter = counter + size(cellarray{loop},1);
end
% loop through each cell
output = zeros(1,counter);
bookmark = 1;
for loop = 1:length(cellarray)
if ~isempty(cellarray{loop})
output(bookmark:bookmark+length(cellarray{loop}(strcmpi(cellarray{loop}.DistributionType,string),:).(VarInt))-1) =...
cellarray{loop}(strcmpi(cellarray{loop}.DistributionType,string),:).(VarInt);
bookmark = bookmark + length(cellarray{loop}(strcmpi(cellarray{loop}.DistributionType,string),:).(VarInt));
end
end
end
0 Comments
Answers (1)
Peter Perkins
on 8 Mar 2018
Daniel, I'm not exactly sure what you are asking, but i think the following might help. All of these kinds of "dot subscripting" are equivalent:
>> t = array2table(rand(2))
t =
2×2 table
Var1 Var2
_______ ________
0.74815 0.083821
0.45054 0.22898
>> t.Var1
ans =
0.74815
0.45054
>> t.('Var1'); % noone would ever actually do this
>> vname = 'Var1'; t.(vname);
>> t.(1);
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!