MATLAB Answers

Abcde
0

How to Rearrange data?

Asked by Abcde
on 30 Jun 2019
Latest activity Answered by Image Analyst
on 30 Jun 2019
I have input .txt file like :
Number Time Symbol
1 0 C
2 0 E
3 0 D
4 0 C
5 0 D
1 1 C
2 1 C
3 1 C
4 1 D
5 1 E
1 2 C
2 2 D
3 2 D
4 2 C
5 2 E
Where "Number"(1-5) was periodic with "Time"(0-2) and I need to calculate count of each "Symbol" with "Time" and I want to output file as .txt like:
Time C D E TOTAL(C+D+E)
0 2 2 1 5
1 3 1 1 5
2 2 2 1 5
Is there a way to get the output file by using MATLAB?
Thanks.

  0 Comments

Sign in to comment.

Products

2 Answers

Answer by David Wilson on 30 Jun 2019
Edited by David Wilson on 30 Jun 2019
 Accepted Answer

Try something like the following: First read in the data file (which I've called numData.txt). I've used your test data above.
inFname = 'numData.txt'
fid = fopen(inFname,'r');
[A] = fscanf(fid,'%i %i %s',[3,inf])';
fclose(fid);
Now provess the data. I've put a few checks in the code below. All going well, you should have a data file called OuputFile.txt. Note that "C" is ascii 67 etc.
%% Now process the data
outFname = 'OutputFile.txt';
fid = fopen(outFname,'w');
fprintf(fid,'%s\n', 'Time C D E Total(C+D+E)');
n = length(A);
if mod(n,5) % check we have multiple of 5
warning('missing data ??')
end
t = A(:,2);
if ~all(diff(t)>=0) % check time is all ascending
warning('time not ascending ??')
end
for i=1:5:n
k = i:i+4;
c = A(k,3);
C = sum(c==67);
D = sum(c==68);
E = sum(c==69);
tot = C+D+E; % should always = 5 ??
fprintf(fid,'%i, %i, %i, %i, %i \n', A(i,2), C,D,E,tot);
end
To check you can do something like: M
>> !type OutputFile.txt
Time C D E Total(C+D+E)
0, 2, 2, 1, 5
1, 3, 1, 1, 5
2, 2, 2, 1, 5

  0 Comments

Sign in to comment.


Image Analyst
Answer by Image Analyst
on 30 Jun 2019

Try importdata(), readtable(), or dlmread().

  0 Comments

Sign in to comment.