How to extract table data using function variable?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Peter Perkins
2018년 3월 8일
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);
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!