Formatting a single row of data into multiple rows

15 次查看(过去 30 天)
I have been using textscan to read a text file composed of numbers. The Data in the file is composed of one long row. I have been trying to find a method to have Matlab count a certain amount of numbers and then begin a new row ( for example, 100 numbers & start a new row every 10 numbers) but have not been able to find one.
fid = fopen('file');
Data = textscan( fid, '%d', 'delimiter', ';');
I assume I will need to put this command in the textscan line as without it this creates a single 1x1 cell. Could I create a loop for this, perhaps, to recognize semi-colons as a delimiter between numbers and newline as a delimiter between rows?

回答(1 个)

dpb
dpb 2017-2-6
编辑:dpb 2017-2-6
Data = cell2mat(textscan( fid, '%d', 'delimiter', ';')); % convert to array from cell
N=10; % size of new array number elements/column
Data=reshape(Data,N,[]).'; % and recast to said size...
This presumes, of course, that mod(numel(Data),N) == 0 as you can't have "jagged" arrays in Matlab. If that isn't so you either must truncate to the multiple of N, fill with NaN or other value to make up the missing elements or use a cell array instead that can have a short row.
ADDENDUM
Again, on the presumption you know your data is commensurate in size, you can do as you first surmised on the initial read--
N=1024;
fmt=repmat('%f',1,N);
data=cell2mat(textscan(fid,fmt,inf));
This has the issue that will error out if there aren't enough data to fill the last row whereas the first will read all the data and give you a chance to fix up the result if desired. This form will return the data up to the point of the error, however, so if the intent is to read M records of N values, then it may be the solution desired.
Of course, again, you'll only get a reshaped output file if you then go ahead and write the data in the desired format to a new file (or overwrite the original which is potentially dangerous if you make a mistake on the way to the forum).
  5 个评论
Guillaume
Guillaume 2017-2-7
"only in the matlab command window"
Absolutely not, the workspace variable data has been reshape into 1024 columns
"It doesn't create a file in the workspace"
The workspace does not contain files. It's not clear what you mean.
dpb
dpb 2017-2-7
Indeed, I noticed the superfluous duplicated lines
data = reshape(Data, N, []);
data = reshape(Data, N, [])
the second of which does nothing the first didn't excepting echo the result to the command window; the LHS was assigned the first time in memory to the variable data in whatever scope it resides...

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by