Hello, I have a string named area in which string are stored as shown below:
1 2296.0 220.9 232.5
2 814.0 344.7 263.9
3 993.0 372.9 241.4
4 2406.0 469.7 228.5
I want to convert this string into array. So I used cellstr(area) but what I got is all these values in one cell only.
' 1 2296.0 220.9 232.5'
' 2 814.0 344.7 263.9'
' 3 993.0 372.9 241.4'
' 4 2406.0 469.7 228.5'
' 4 2406.0 469.7 228.5'
What I want is every value in different cell. Like, in first column 1,2,3,4 etc. In 2nd column 2296.0, 814.0 etc. How can I do this?

 채택된 답변

Walter Roberson
Walter Roberson 2017년 8월 14일

0 개 추천

t = regexp(regexprep(cellstr(area), '^\s+', ''), '\s+', 'split');
CC = str2double(vertcat(t{:}));

추가 답변 (2개)

Jan
Jan 2017년 8월 13일
편집: Jan 2017년 8월 13일

0 개 추천

Perhaps you mean:
D = sscaf(area, '%g', [4, inf]).';
C = num2cell(D)
Do you "cell", or is D the wanted matrix already?

댓글 수: 1

Hello Sir, I tried what you suggest but I shows answer like
[1.2341e+11] [2] [1] [8.2116e+43]
But I want every value in a different cell. I don't know what is this? I added my area file in question in case you need. thanks

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

Naseeb Gill
Naseeb Gill 2017년 8월 13일

0 개 추천

Ok I got it. I just use below line:
CC = str2num(area);
And I got my expected array.

댓글 수: 5

... until the time someone writes
delete('*.*')
into the file...
Naseeb Gill
Naseeb Gill 2017년 8월 14일
Pardon me, I didn't get you. Can you please explain what you want to convey by delete(.). Because delete is used to delete files and doesn't want to delete files, I just want to change into an array.
str2num(area) is the same thing as
eval( [ '[', area, ']' ] )
so if your file happened to have any text in them, the text would be executed as commands, even if those commands were to reformat your hard drive. It is therefore a good idea to not use str2num() unless you have already verified that the text you are converting contains only numbers (possibly together with the list building characters such as '[', ';', ',', and ']' )
The solution I posted uses str2double, which will never execute commands, and does not even permit commas or even multiple numbers in the same string, only pure numbers with possible leading or trailing spaces.
Naseeb Gill
Naseeb Gill 2017년 8월 14일
Oh !!! thank you for this knowledge. I will be careful for this.
Stephen23
Stephen23 2017년 8월 14일
편집: Stephen23 2017년 8월 14일
@NASEEB SINGH: str2num hides eval inside, and eval is a bit rsky to use as it can execute arbitrary code (also is slow, hard to debug, etc): https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval

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

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

질문:

2017년 8월 13일

편집:

2017년 8월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by