- "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
46 views (last 30 days)
Show older comments
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
13 Comments
Accepted Answer
per isakson
on 1 Nov 2017
Edited: per isakson
on 1 Nov 2017
"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.
More Answers (2)
Walter Roberson
on 1 Nov 2017
You have fixed width fields. You should see https://www.mathworks.com/help/matlab/ref/fixedwidthimportoptions.html if you have R2017a or later.
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!