How to extract table data based on column values?

조회 수: 139 (최근 30일)
Struggling in MATLAB
Struggling in MATLAB 2022년 3월 17일
답변: Struggling in MATLAB 2022년 3월 17일
I have a table, part of which is displayed. I have attached the table in the question. The entries of the tables are 1*1 cell array.
I am trying to extract all the rows based on 'date'.
test_data((cell2mat(test_data.date) == '02/10/2022', :)
It gives me error "Row index exceeds table dimensions." I also get error for 'subjectid' or 'mazenumber' column.
But it works for "feeder" column.
>> test_data(cell2mat(test_data.feeder) == '4',:)
How do I fix this?

채택된 답변

Eric Sofen
Eric Sofen 2022년 3월 17일
One thing to watch out for is that the char vectors contained in the cell arrays (celltrs) can vary in the number of characters, causing cell2mat to fail. As @Jon suggested, strcmp between your char vector of interest and the cellstr variable is going to be much more robust.
Going a step further, it may make sense to convert some of your variables to more "modern" types:
subjectid - string
mazenumber - categorical
feeder - categorical or double
date - datetime
That said, depending on what you're doing with the data and how you're interacting with the database, it may not make sense to do the conversion.
  댓글 수: 1
Struggling in MATLAB
Struggling in MATLAB 2022년 3월 17일
편집: Struggling in MATLAB 2022년 3월 17일
Hi Eric! Thanks for your response. I have attached the in the original question. I tried using 'strcmp', But that did not work either. Both the elements I am comparing are 'char' vector.
>> cell2mat(test_data.mazenumber(1))
ans =
'maze 2'
>> class(cell2mat(test_data.mazenumber(1)))
ans =
'char'
>> class('maze 2')
ans =
'char'
>> test_data(strcmp(cell2mat(test_data.mazenumber),'maze 2',:));
Unrecognized function or variable 'strcmp'. % getting this error
I'll try to convert the variables now and see if that works.

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

추가 답변 (2개)

Jon
Jon 2022년 3월 17일
Could be you should be using strcmp rather than == to compare the strings
It's a little hard to know exactly how you have the data stored in the table.
Please save your table using
save test_data.mat test_data
and attach the resulting test_data.mat so we can see what is going on.
  댓글 수: 1
Struggling in MATLAB
Struggling in MATLAB 2022년 3월 17일
편집: Struggling in MATLAB 2022년 3월 17일
Hi Jon! Thanks for your response. I have attached the in the original question.

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


Struggling in MATLAB
Struggling in MATLAB 2022년 3월 17일
Thanks everyone for your comments. The problem is fixed now. I used the following code to get around.
test_data.date = datetime(test_data.date, 'InputFormat','MM/dd/yyyy');
all_trials_on_test_data = test_data((test_data.date) == '10-Feb-2022',:);

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by