How do I find and replace text in an imported table?

조회 수: 10 (최근 30일)
Darla Bonagura
Darla Bonagura 2019년 8월 28일
댓글: Lorenz Bankel 2021년 3월 24일
I've imported data from an Excel file and have it as a table (DemographicsData). I would now like to find all cells that contain 'Male' and replace them with '1' and 'Female' with '2'. How do I run this command? I'm new with MATLAB and would appreciate any help.

채택된 답변

Adam Danz
Adam Danz 2019년 8월 28일
편집: Adam Danz 2019년 8월 28일
Presumably there's a column in your table for sex|gender and the Male|Female categories are listed in that column. You could use findgroups() to automatically replace M|F with group numbers.
% assuming the table is named T and the
% column is named "sex"
T.sex = findgroups(T.sex);
Another option is to assign those values directly,
T.sex(strcmpi(T.sex,'Male')) = {1};
T.sex(strcmpi(T.sex,'Female')) = {2};
  댓글 수: 9
Adam Danz
Adam Danz 2021년 3월 23일
편집: Adam Danz 2021년 3월 23일
@Lorenz Bankel thanks a lot for taking the time to point out that error. I updated that comment to fix the error.
Explanation of my error:
Since matlab does not allow subscripting as in T(ind) into a table (as of r2021a), I was incorrectly subscripting rows and columns using T(row,col) which selects all rows and columns listed, not just the combinations of (row,col) indices.
Explanation of the correction:
Instead, the table is now converted to a cell array and sub2ind is used to get the linear indices that correspond to the selected rows and column. The updated cell array then replaces the values in the table.
Lorenz Bankel
Lorenz Bankel 2021년 3월 24일
thanks a lot for the explanantion and the solution. Works perfektly!

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by