Convert cell array of character vectors to evaluable expressions

조회 수: 2 (최근 30일)
Alec Poulin
Alec Poulin 2018년 9월 27일
편집: Alec Poulin 2018년 9월 27일
I have a cell array of character vectors:
>> list
list =
5×1 cell array
{'10^{-4}'}
{'10^{-3}'}
{'10^{-2}'}
{'10^{-1}'}
{'10^{0}' }
I want to convert these vectors into the numbers they represent. I tried to use str2num, but it doesn't work with arrays or cell arrays. Using str2double, I get a cell array of NaNs because the character vectors are not only numbers, but rather expressions to evaluate. So I tried to use eval. This is my first attempt:
>> eval(list)
Error using eval
Must be a string scalar or character vector.
So I thought using cellfun would do the job because eval would be fed only one vector at a time, but instead I get this:
>> cellfun(eval, list)
Error using eval
Not enough input arguments.
After further tests, it seems like eval doesn't work with cellfun or arrayfun, which doesn't make sense to me. Is there any way to convert my expressions into numbers?
  댓글 수: 1
Stephen23
Stephen23 2018년 9월 27일
편집: Stephen23 2018년 9월 27일
You have avoided mentioning the elephant in the room: none of the character vectors use valid MATLAB syntax, so none of your methods would ever work until you do something with those vectors to convert them into valid MATLAB syntax. Even better would be to avoid eval and friends and just parse the values yourself.

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

채택된 답변

Stephen23
Stephen23 2018년 9월 27일
편집: Stephen23 2018년 9월 27일
This is pretty easy with standard string parsing tools, e.g. sscanf:
>> C = {'10^{-4}';'10^{-3}';'10^{-2}';'10^{-1}';'10^{0}'};
>> V = sscanf([C{:}],'%d^{%d}');
>> Z = V(1:2:end).^V(2:2:end)
Z =
0.00010000
0.00100000
0.01000000
0.10000000
1.00000000
You will find that this is quite fast too (1e4 iterations):
Elapsed time is 0.281599 seconds. % my answer
Elapsed time is 6.407189 seconds. % Fangjun Jiang's answer.
Also, because it does not use eval in any way (e.g. str2num), it is secure and does not impede MATLAB's JIT engine.

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2018년 9월 27일
NewList=strrep(list,'{','(');
NewList=strrep(NewList,'}',')');
cellfun(@str2num,NewList)
  댓글 수: 3
Alec Poulin
Alec Poulin 2018년 9월 27일
Can you talk a bit about these disadvantages?
Stephen23
Stephen23 2018년 9월 27일
편집: Stephen23 2018년 9월 27일
"Can you talk a bit about these disadvantages"
Sure. The main disadvantages of eval (slow, security risk, etc) are covered here:

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by