How to extract table data using function variable?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Peter Perkins
el 8 de Mzo. de 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);
2 comentarios
Stephen23
el 8 de Mzo. de 2018
See also the MATLAB documentation:
Daniel Bridges
el 9 de Mzo. de 2018
Editada: Daniel Bridges
el 9 de Mzo. de 2018
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!