Use logical indexing to create a new structure containing specific data from an excel file

조회 수: 3 (최근 30일)
The question asks to create a new structure from a data set for dogs. And do the same for cats. An excel file was given which a multitude of data (101 rows and 15 columns). The columns denoted things such as age, size, name, etc., in which one was designated for "species", which listed either dog or cat. The excel file was converted to a structure with the table2struct function.
file1 = readtable('Random.xlsx'); %use readtable function to load caregiver data
table = table2struct(file1)
How would I go about extracing all the data just for the dogs. No looping.

채택된 답변

Voss
Voss 2022년 2월 20일
file1 = readtable('Random.xlsx') %use readtable function to load caregiver data
file1 = 3×5 table
Age Size Name Species Is_A_Good_Boy_or_Girl ___ __________ ______________ _______ _____________________ 2 {'small' } {'Fido' } {'Dog'} true 4 {'large' } {'Mr Pickles'} {'Cat'} true 9 {'medium'} {'Rex' } {'Dog'} true
table = table2struct(file1)
table = 3×1 struct array with fields:
Age Size Name Species Is_A_Good_Boy_or_Girl
dog_data = table(strcmp({table.Species},'Dog'))
dog_data = 2×1 struct array with fields:
Age Size Name Species Is_A_Good_Boy_or_Girl
[dog_data.Age]
ans = 1×2
2 9
{dog_data.Size}
ans = 1×2 cell array
{'small'} {'medium'}
{dog_data.Name}
ans = 1×2 cell array
{'Fido'} {'Rex'}
[dog_data.Is_A_Good_Boy_or_Girl]
ans = 1×2 logical array
1 1
  댓글 수: 2
Cam B
Cam B 2022년 2월 20일
Thank you. Also, how would I go about finding the number of dogs?
Voss
Voss 2022년 2월 20일
You're welcome!
file1 = readtable('Random.xlsx'); %use readtable function to load caregiver data
table = table2struct(file1);
% using the full struct array:
nnz(strcmp({table.Species},'Dog'))
ans = 2
% or, after creating the dog struct array:
dog_data = table(strcmp({table.Species},'Dog'));
numel(dog_data)
ans = 2

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by