how to execute str2num or str2double in matlab?

조회 수: 5 (최근 30일)
MEENAL SINGHAL
MEENAL SINGHAL 2018년 5월 9일
편집: Stephen23 2018년 5월 9일
I am having trouble using commands str2num.
I have a character
t='2'
'u1'
'u2 '
I used the command p=str2double(char(t)). Right now if I use str2num, a null array appears in the output whereas using str2double gives NaN in output. While searching about these I learned that these character values are not converted to numbers.
I wanted p to store values [2, 1, 2]. How can I do that? Thanks for reading...
  댓글 수: 4
per isakson
per isakson 2018년 5월 9일
편집: per isakson 2018년 5월 9일
Hint:
t = { '2' 'u1' 'u2 '};
c = regexp( t, '[\d ]+', 'match' );
p = cellfun( @str2double, c )
outputs
p =
2 1 2
MEENAL SINGHAL
MEENAL SINGHAL 2018년 5월 9일
편집: MEENAL SINGHAL 2018년 5월 9일
Thanks @per isakson for the hint [and for editing my question :)]. It works individually in command prompt but gives a error saying "set UniformOutput to false" when I run the same with the complete code.

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

채택된 답변

Stephen23
Stephen23 2018년 5월 9일
편집: Stephen23 2018년 5월 9일
Simple, and possibly the most efficient way:
>> t = {'2','u1','u2 '};
>> sscanf([t{:}],'%du')
ans =
2
1
2
  댓글 수: 2
MEENAL SINGHAL
MEENAL SINGHAL 2018년 5월 9일
Thanks Stephen Cobeldick for answering. The problem is solved for
t='2'
'u1'
'u2 '
But what if I have
t= 'u0*2 '
'u1*2 '
'u2*2 '
Now I want 'p' to store [0*2 1*2 2*2] ,i.e., [0 2 4]. How can I do that?
Stephen23
Stephen23 2018년 5월 9일
편집: Stephen23 2018년 5월 9일
@MEENAL SINGHAL: Perhaps you are asking about how to write a maths parser, which in general is not a trivial task. What operators do you expect to have? For simple multiplication:
>> t = {'u0*2','u1*2','u2*2'};
>> v = sscanf([t{:}],'u%d*%d');
>> v(1:2:end).*v(2:2:end)
ans =
0
2
4

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by