# Write a well tabulated txt file

1 view (last 30 days)

Show older comments

This is my code:

v_cutin=2.5;

v_cutout=15;

v_rated=5.5;

v=linspace(v_cutin,v_cutout,15);

omega_rpm=linspace(1,600,200);

dataset_lin=importdata('dataset_lin.mat');

dataset_red_lin=NaN*ones(((length(omega_rpm)/10)+1)*length(v)+length(v)-1,6);

x=1;

row=0;

y=1;

stop=0;

for i=1:length(dataset_lin)

if isnan(dataset_lin(i,1))==0

row=row+1;

stop=0;

elseif isnan(dataset_lin(i,1))==1 && stop<1

step=floor(row/10);

check=mod(row,10);

if check==0

dataset_red_lin(y:1:y+9,:)=compose("%.3f",dataset_lin(x:step:(i-1),:));

dataset_red_lin(y+10,:)=NaN*ones(1,6);

x=i+1;

row=0;

y=y+11;

elseif check>0

dataset_red_lin(y:1:y+10,:)=compose("%.3f",dataset_lin(x:step:(i-check),:));

dataset_red_lin(y+11,:)=NaN*ones(1,6);

x=i+1;

row=0;

y=y+12;

end

stop=stop+1;

elseif stop==1

i=length(dataset_lin);

end

end

A = dataset_red_lin;

C = num2cell(A);

idx = isnan(A);

C(idx) = {''};

writematrix(string(C), 'dataset_red_lin.txt', 'Delimiter', 'tab');

I need the conversion to cell in order to replace the NaN values with blank spaces. However, the resultant txt file is not well tabulated because there are some numbers which has no decimal digits. Ho do I can figure out the problem?

##### 4 Comments

_
on 4 Dec 2021

### Answers (1)

DGM
on 4 Dec 2021

Edited: DGM
on 4 Dec 2021

dataset_lin=importdata('dataset_lin.mat');

stepsize0 = 3; % initial row step size

blocksize = 11; % number of rows per output block

% find block extents

nanrows = find(all(isnan(dataset_lin),2));

nanrows(find(diff(nanrows)==1)+1) = [];

nanrows = [0; nanrows];

% process blockwise

fid = fopen('testfile.txt','w');

for b = 2:numel(nanrows)

thisblock = dataset_lin(nanrows(b-1)+1:stepsize0:nanrows(b)-1,:);

thisblock = thisblock(1:blocksize,:);

fprintf(fid,'%6.3f\t%8.3f\t%5.3f\t%5.3f\t%8.3f\t%7.3f\n',thisblock.');

fprintf(fid,'\n');

stepsize0 = stepsize0 + 1;

end

fclose(fid);

##### 0 Comments

### See Also

### Community Treasure Hunt

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

Start Hunting!