Splitting cell array of both strings and numbers by a delimiter

조회 수: 2 (최근 30일)
Melissa
Melissa 2014년 12월 11일
댓글: Guillaume 2014년 12월 11일
Hello,
I have a cell array that consists of both strings and numbers. I need to split into two different columns by the delimiter '~' However, I am not able to use regexp, as the cell array must all be strings. And I can't use num2str or str2num because half are strings and half are numbers, and it creates an error message. I am attaching my .mat file so you may get an idea of what I'm working with.
Please let me know what I can do to split this cell array into two different columns by the delimiter '~' For the elements that are NaN, I would like both columns to say NaN
Thank you for your help,
Melissa
  댓글 수: 3
Melissa
Melissa 2014년 12월 11일
I found the way to change the numbers into strings! I had to use cellfun but with the uniform output changed to false :
Depthcm = cellfun(@num2str, Depthcm,'UniformOutput','false');
Now I have a cell array of strings, and I can now use regexp. However, I am a bit confused about how I can split them into two separate columns while also including the NaN's. Because if I split it with this line:
Y = regexp(Depthcm,'\~','split');
I get a 1x2 cell within each of the Y elements, except for the NaN indices.
Therefore, I would like two columns like this:
A = [0 0 0 NaN 2 NaN NaN]; B = [20 20 5 NaN 4 NaN NaN];
Guillaume
Guillaume 2014년 12월 11일
If you've changed the NaN into a single string, then you're back to your previous question.
Or you can do what I've done in my answer below.
In any case, when processing data, it is better to always generate that data in a consistent way. In your case, that means always have string consisting of two numbers surrounding ~, even if these numbers are NaN. That is, you would have been better off writing 'NaN~NaN' in your cell array instead of 'NaN' or NaN.
Side note: there's no need to escape ~ in the regular expression. I'm surprised matlab accepts it.

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

채택된 답변

Guillaume
Guillaume 2014년 12월 11일
The simplest thing would be to convert these NaNs into strings of 'NaN~NaN' and then use the same algorithm as in my previous answer to convert the cell array:
Depthcm(cellfun(@(x) isnumeric(x) && isnan(x), Depthcm)) = {'NaN~NaN'};
splitdepth = regexp(Depthcm, '~', 'split');
bounds = str2double(vertcat(splitdepth{:}));
  댓글 수: 1
Melissa
Melissa 2014년 12월 11일
Yes! that is exactly what I was looking for!
Much easier and logical than my previous comment :)
Thank you so much

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by