Reputation: 4581
I want to read a text file which contains English words and sentences. I want to store the characters in this text file in a matrix with a specific size.
Suppose my text file is named textfile.txt
and looks like this:
Creating strings in a regular MATLAB® array requires that all strings in the array be of the same length. This often means that you have to pad blanks at the end of strings to equalize their length. However, another type of MATLAB array, the cell array, can hold different sizes and types of data in an array without padding. Cell arrays provide a more flexible way to store strings of varying length.
This is part of the article "Cell Arrays of Strings" in the Matlab documentation.
I specified a column size of 16, so the number of rows will be the total numbers of characters divided by the colunm size (16).
My result matrix should look like this:
c r e a t i n g s t r i n g
s t r i n g s i n a r e g u l a ... and so on
Space and new lines should also be considered while storing the characters in the matrix.
Upvotes: 0
Views: 185
Reputation: 114796
You can read the entire textfile.txt
as a single vector of characters (of size 1-by-n
where n
is the number of characters).
Then you should pad this vector with ceil(n/16)*16 - n
spaces to make the length of the vector divisible by 16.
Finally, you can reshape
it:
myMatrix = reshape( myVec, 16, [] ).';
Upvotes: 2