Change text to numbers in a cell

조회 수: 3 (최근 30일)
Mike Mierlo van
Mike Mierlo van 2020년 5월 7일
댓글: Mike Mierlo van 2020년 5월 11일
Hi all,
Lets say I have 4 x 2 cell matrix A:
1 'text one' 'text two'
2 '5' 'text two'
3 'text one' 'text two'
4 '10' 'text two'
I want the result of a 4 x 2 cell matrix A of all doubles, exept for the last column. The 'text one' has to be replaced by 1 (double):
1 1 'text two'
2 5 'text two'
3 1 'text two'
4 10 'text two'
When I use a for-loop and if-statement I get the error that matrix dimensions must agree. Below is my faulty code:
for i = 1:size(A,1)
if A{i,2} == 'text one'
A{i,2} == 1
else
A{i,2} == str2double(A{i,2})
end
end

채택된 답변

Akira Agata
Akira Agata 2020년 5월 8일
How about the following?
B = replace(A,'text one','1');
B = cellfun(@str2double,B(:,1:end-1),'UniformOutput',false);
A = [B,A(:,end)];
  댓글 수: 3
Akira Agata
Akira Agata 2020년 5월 8일
Could you upload your original cell arrya A?
I have assumed as follows and my code works agains it.
A = {...
'text one', 'text two';
'5', 'text two';
'text one', 'text two';
'10', 'text two'};
Mike Mierlo van
Mike Mierlo van 2020년 5월 8일
Now it works. Because I tried some things, my A(:,2) was converted to doubles with NaN's instead of text. Resetting A to the original cell was the solution. thank you!

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

추가 답변 (1개)

madhan ravi
madhan ravi 2020년 5월 7일
편집: madhan ravi 2020년 5월 7일
V = str2double(string(A)); % <2016a
V(isnan(V)) = 1
  댓글 수: 4
madhan ravi
madhan ravi 2020년 5월 8일
Dude when did you edit your question? For sure you edited it after I answered!
Mike Mierlo van
Mike Mierlo van 2020년 5월 11일
Madhan Ravi. Yes, I editted it after your answer. Your answer worked perfectly on my simplified problem, but I simplified it so far that your solution did not work on my actual table, that consisted of more text columns too.
Walter Roberson. Yes A has more numeric values too. I solved it by converting them to strings for the needed operation.

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

카테고리

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