필터 지우기
필터 지우기

Formatting a single row of data into multiple rows

조회 수: 15 (최근 30일)
Aaron Smith
Aaron Smith 2017년 2월 6일
댓글: dpb 2017년 2월 7일
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