- "array A" is that a cell array?
- Could you provide a tiny example?
- Why import a text file with numerical data into character data and convert to numerical in a second step?
how to use the str2num for the whole array at once
39 次查看(过去 30 天)
显示 更早的评论
Dear all, when I read a text file and import it as an array A, sometimes I use the function str2num to return the imported vectors into a numerical form, but I need to do it for each vector alone. is there anyway please to reshape the whole array A into a numeric matrix at one time? like can i use the str2num to the whole matrix A and call it B for example?
thank you
采纳的回答
per isakson
2017-11-1
编辑:per isakson
2017-11-1
"I have older than what Mr Walter said" Thus the old way
Read the file and convert the content to an old time string array, str
fid = fopen( 'NewTextDocument.txt' );
cac = textscan( fid, '%s', 'Delimiter', '\n' );
fclose( fid );
str = char( cac{1} );
str( str==' ' ) = '0';
Inspect str
>> whos str
Name Size Bytes Class Attributes
str 50x105 10500 char
and
>> str(1,:)
ans = W39000779310707010002000001802010029008000000000000000000000000000000000000000000000000000000000000000000
Now you have a string array with the width of the longest row. The function, char, padded with space, which I replaced by the character '0'. (I padded one line of the text file with "0" up till the column 105.)
Now convert columns of the character array to numerical column vectors
Vehicle_Class = str2num( str(:,20:21) );
D_Axle_Weight = str2num( str(:,49:51) );
and inspect the result
>> whos Vehicle_Class D_Axle_Weight
Name Size Bytes Class Attributes
D_Axle_Weight 50x1 400 double
Vehicle_Class 50x1 400 double
With these pieces of code I think you can make your script work.
更多回答(2 个)
Walter Roberson
2017-11-1
You have fixed width fields. You should see https://www.mathworks.com/help/matlab/ref/fixedwidthimportoptions.html if you have R2017a or later.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!