필터 지우기
필터 지우기

I want to replace strings in a column of a structure (see the picture) with numbers/codes. Can someone help with this??

조회 수: 1 (최근 30일)
I have several strings in a column of a structure. They were imported to matlab through eeglab. The strings that I'm interested in are "stm+" and "resp" (you can see the picture attached). I want to replace them with number 1 and 3, respectively.
  댓글 수: 2
Walter Roberson
Walter Roberson 2023년 9월 14일
Do you want to replace them with "1" and "3" or with numeric 1 and 3? Because if you want to replace them with numeric 1 and 3, you would have to deal with the fact that the rest of the column is going to remain string.
Marco
Marco 2023년 9월 14일
They need to be numerical values. Your answer below worked well though.

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

채택된 답변

Walter Roberson
Walter Roberson 2023년 9월 14일
codestrings = {'bgin', 'resp', 'stm+', 'TRSP'};
codevals = [-2, 3, 1, -4];
[found, index] = ismember(YourTable.columnlabel, codestrings);
codes = nan(height(YourTable), 1);
codes(found) = codevals(index(found));
This inserts nan for any unrecognized string, and whatever value is in codevals for recognized strings.
  댓글 수: 2
Marco
Marco 2023년 9월 14일
Thank you! I could use only the first 3 lines. FYI, I run this:
index=num2cell(index);
and
[YourTable.columnlabel]=index{:};
So I could replace the whole column in the structure I need.
Thanks!
Walter Roberson
Walter Roberson 2023년 9월 14일
You could have just used
YourTable.columnlabel = codes;
codes was already constructed as a column vector the correct size (the nan initialization took care of that), and when you use dot notation to assign to a table variable, the type of the variable will be changed if needed.

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

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by