Access data from table and assign to variables
조회 수: 6 (최근 30일)
이전 댓글 표시
Hi, I am making a program with excel file already converted to table and now I need to code such that when a user gives an input a certain coloumn is taken and then assign certain variables to some particular blocks in that row.
example:
Vehicle speed fuel
Car 50 2
Bike 20 1
Cycle 5 0
Like user gives input as Bike. then I need to assign variables created like speed and fuel to use in further equations.
댓글 수: 4
Stephen23
2021년 8월 27일
"...then I need to assign variables created like speed and fuel to use in further equations."
Why not just access the data directly from the table?
채택된 답변
Ive J
2021년 8월 27일
편집: Ive J
2021년 8월 27일
This might work
tab = table({'Car'; 'Bike'; 'Cycle'}, [50; 20; 5], [2; 1; 0],...
'VariableNames', {'Vehicle', 'speed', 'fuel'})
filterIn = 'Bike'; %input('what to filter? ', 's');
idx = ismember(tab.Vehicle, filterIn);
if ~any(idx)
fprintf('oops, not found!\n')
return
end
dataTable = tab(idx, :);
dataStruct = table2struct(dataTable, 'ToScalar', true);
as table:
disp(dataTable)
or struct:
disp(dataStruct)
추가 답변 (1개)
Campion Loong
2021년 8월 30일
Picking up from @Ive J's example, but use 'Vehicle' as Row Labels to take advantage of native table indexing:
t = table([50; 20; 5], [2; 1; 0], 'VariableNames', ["speed", "fuel"], 'RowNames', ["Car"; "Bike"; "Cycle"])
t("Bike", ["speed", "fuel"]) % or if you want all variables, t("Bike", :)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!