Substitute string to double

조회 수: 5 (최근 30일)
Juan Castillo
Juan Castillo 2020년 9월 17일
댓글: Juan Castillo 2020년 9월 20일
Hi everyone, very simple question here:
I have this:
Acell =
3×3 cell array
'0+1/R1' '0-1/R1' '1'
'0-1/R1' '0+1/R1+1/R2' '0'
'1' '0' '0'
Apart from that, I have this:
R1 = '1000';
R2 = '1000';
My goal is to convert the original string to a double array so I could perform calculations afterwards, like this:
A = [ 1/1000 -1/1000 1; -1/1000 1/1000+1/1000 0; 1 0 0;];
What I tried so far was:
Acell = strrep(Acell,'R1','1000');
Acell = strrep(Acell,'R2','1000');
A = str2double(Acell);
Obtaining:
A =
NaN NaN 1
NaN NaN 0
1 0 0
Any thoughts? This is just a little example, my idea is doing that job for much more elements so I'm not sure about using 'strrep' too.
Many thanks in advance

채택된 답변

Stephen23
Stephen23 2020년 9월 18일
편집: Stephen23 2020년 9월 18일
>> A = {'0+1/R1','0-1/R1','1';'0-1/R1','0+1/R1+1/R2','0';'1','0','0'};
>> A = strrep(A,'R1','1000');
>> A = strrep(A,'R2','1000');
>> B = cellfun(@str2num,A)
B =
0.0010 -0.0010 1.0000
-0.0010 0.0020 0
1.0000 0 0
Warning: will run arbitrary commands, use at your own risk!
Rather than storing functions as strings, perhaps they should be stored as function handles. Then you can simply and effiiciently call them with the required input data (as numeric, of course!).
>> A = {'0+1/R1','0-1/R1','1';'0-1/R1','0+1/R1+1/R2','0';'1','0','0'};
>> F = cellfun(@(s)str2func(['@(R1,R2)',s,';']),A,'uni',0); % convert to function handle
>> B = cellfun(@(f)f(1000,1000),F) % call all with the same inputs
B =
0.0010 -0.0010 1.0000
-0.0010 0.0020 0
1.0000 0 0
>> F{1,2}(20,30) % call function {1,2}
ans =
-0.0500
  댓글 수: 1
Juan Castillo
Juan Castillo 2020년 9월 20일
Thank you very much!!

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

추가 답변 (1개)

madhan ravi
madhan ravi 2020년 9월 17일
편집: madhan ravi 2020년 9월 17일
Requires Symbolic Math Toolbox:
Wanted = str2sym(regexprep(Acell, {'R1', 'R2'}, {R1, R2}))
%or for older versions
Wanted = sym(regexprep(Acell, {'R1', 'R2'}, {R1, R2})) % not tested
  댓글 수: 2
Juan Castillo
Juan Castillo 2020년 9월 18일
Hi, thanks for your answer, but still get an error doing whatever you said:
Error using regexprep
All cells must be char row vectors.
madhan ravi
madhan ravi 2020년 9월 18일
Works in 2020a just fine.

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

카테고리

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

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by