MATLAB Answers

How can I call half of text by using "textread" ? (1*4096 matrix to 1*2048 matrix)

1 view (last 30 days)
James James
James James on 16 Oct 2021
Edited: dpb on 17 Oct 2021
How can I call half of text by using "textread" ? (1*4096 matrix to 1*2048 matrix)
  1 Comment
dpb
dpb on 16 Oct 2021
x=textread('YourFile.dat'); % read the file
x=x(1:fix(size(x,1)/2)); % save first half (will deal with numel(x) odd as well)

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 16 Oct 2021
I have never used textread, however that could be described in the format string, for example —
formatStr = [repmat('%f',1,2048) repmat('%*f',1,2048)];
The addition of the ‘*’ suppresses those fields from being read (assuming they are all numeric). See the doucmentation on format for an extended discussion.
..
  1 Comment
dpb
dpb on 16 Oct 2021
That works, but
y=textread('YourFile.dat','%f',2048);
is simpler.
I've not compared, but I'd guess the other solution of reading the full file and decimating the unwanted half is probably faster.
"I have never used textread..."
While deprecated, it has its place -- for one thing, it returns the numeric array directly instead of having to cast a cell array with cell2mat as must with textscan. Also it uses the filename directly instead of the need to open and close a file handle.
The advantages have been made less of ones with the recent introduction of readmatrix and friends, however.
The disadvantage of textread is that it does perform more slowly than the later reincarnations as MathWorks has not done anything to improve it; it's around only for the backwards compatibility issues of removing it since it has such a long and storied history.
OTOH, textread has one very significant feature that it will, without an explicit format string being given, return an input file array in the same shape as the file structure; textscan has a penchant for not always doing that or have to provide the precise format string to match the file structure -- which may not always be known a priori.
>> writematrix(rand(256,1),'testfile.dat') % some random data
>> x=textread('testfile.dat'); % read whole thing
>> y=textread('testfile.dat','%f',128); % now read only half
>> whos x y
Name Size Bytes Class Attributes
x 256x1 2048 double
y 128x1 1024 double
>> all(y==x(1:numel(y)),'all') % the same data obtained, just half as much
ans =
logical
1
>>

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!

Translated by