How to convert string to matrix
古いコメントを表示
Hi!
From text file I have read matrix and I got string
A=55 3@ 4 5@ 47 89@ 33 12@
where '@' means it's new row. How will I make matrix from this string to look like this
A =
55 3
4 5
47 89
33 12
so A is size 4x2 class double
Please if anyone knows the answer help me
採用された回答
その他の回答 (2 件)
Andrei Bobrov
2014 年 12 月 20 日
A='55 3@ 4 5@ 47 89@ 33 12@'
out = reshape(str2double(regexp(A,'\d*','match')),2,[])'
Image Analyst
2014 年 12 月 20 日
Here's yet another way:
A='55 3@ 4 5@ 47 89@ 33 12@' % Create sample data.
intA = sscanf(A, '%d %d@') % Make string into numerical array.
s=reshape(intA, [numel(intA)/2, 2]) % Shape into two column matrix.
Note, none of the methods given are that robust in that they don't check to see that A has an even number of integers. For robust code, you need to check for that. It's not bulletproof code unless you are prepared to handle things like that - inputs like A='55 3@ 4 5@ 47 89@ 33@' for example.
8 件のコメント
Lolipop
2014 年 12 月 20 日
Image Analyst
2014 年 12 月 21 日
Well, you should have said that in the beginning - no one planned for that.
In that case, the best answer is an adaptions of Andrei's:
clc;
A='55 3@ 4 5@ 47 89@ 33 12@' % Create sample data.
atLocation = find(A=='@');
numNumbers = 1+sum(A(1:atLocation)==' ')
out = reshape(str2double(regexp(A,'\d*','match')), numNumbers,[])'
A='5 5 3@ 4 5 5@ 4 7 89@ 3 8 12@'
atLocation = find(A=='@');
numNumbers = 1+sum(A(1:atLocation)==' ')
out = reshape(str2double(regexp(A,'\d*','match')), numNumbers,[])'
A='5 1 2 2 3@4 3 3 4 5@4 7 8 7 9@4 44 3 3 12@'
atLocation = find(A=='@');
numNumbers = 1+sum(A(1:atLocation)==' ')
out = reshape(str2double(regexp(A,'\d*','match')), numNumbers,[])'
If this helps, please "Vote" for my and Andrei's answers.
Star Strider
2014 年 12 月 21 日
I did. We’ll have to wait for ‘delila’ to return.
Lolipop
2014 年 12 月 21 日
Image Analyst
2014 年 12 月 21 日
There is a function called strtrim() that you should know about. You can use it:
A='79 197 @ 80 197 @ 81 198 @ 82 198 @ 83 199 @';
atLocation = find(A=='@');
trimmedString = strtrim(A(1:atLocation-1))
numNumbers = 1+sum(trimmedString==' ')
out = reshape(str2double(regexp(A,'\d*','match')), numNumbers,[])'
This works for all 3 cases that you've specified so far. Now, what are the remaining cases? We'd rather not modify the code case by case until it works for all cases. We'd like to know all possible cases in advance . It will save both you and us time.
doni yandra
2015 年 10 月 30 日
when I input the value of A with an edit text.. why uitable didn't show anything ?
Image Analyst
2015 年 10 月 30 日
Only Walter has the Crystal Ball Toolbox. The rest of us will need to see your code in a more direct manner, like pasted back here or to a brand new question.
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!