Want to calculate the mean value of each row but found error "Number of columns on line 2 of ASCII file must be the same as previous lines" ?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hallo i want to ask about my error script, So i want to calculate the mean value of each row in the file from column 4 and each row doesn't has the same number of column. I used this script
clear;
clc;
format short;
f = dir('D:\full_Data_Cryosat_c2p0004.txt');
for A = 1 : length(f)
D=f(A).name;
ff=D(:,19:25);
data = load(D);
data(isnan(data)) = 0;
averaged = zeros( size(data,1), 4);
averaged(:,1) = data(:,1);
for j = 1 : size(data,1)
averaged(j, 4) = mean( data(j, 4:end) );
end
file = fopen(strcat('MSL_',D ),'w');
fprintf(file,'%12.6f %12.6f\n', averaged' );
fclose(file);
end
Sample of my file in the attachments file.
But found error like this
Error using load
Number of columns on line 2 of ASCII file full_Data_Cryosat_c2p0004.txt
must be the same as previous lines.
Error in script_msl (line 11)
data = load(D);
Thanks for helping me out guys
댓글 수: 0
채택된 답변
Walter Roberson
2021년 9월 28일
편집: Walter Roberson
2021년 9월 28일
Mean value of each column (I misread at some point)
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/752349/full_Data_Cryosat_c2p0004.txt';
S = readlines(filename);
Snum = cellfun(@(s) sscanf(s, '%f', [1 inf]), S, 'uniform', 0);
longest = max(cellfun(@length, Snum));
padded = cell2mat(cellfun(@(s) [s, nan(1,longest-numel(s))], Snum, 'uniform', 0));
size(padded)
means = mean(padded(:,4:end), 'omitnan')
댓글 수: 7
Walter Roberson
2021년 10월 20일
clear;
clc;
format short;
f = dir('D:\full_Data_Cryosat_c2p0004.txt');
readlines = @(F)regexp(fileread(F),'\r?\n','split');
for A = 1 : length(f)
D = f(A).name;
ff = D(:,19:25);
S = readlines(D);
data = cellfun(@(s) sscanf(s, '%f', [1 inf]), S, 'uniform', 0);
mask = cellfun(@length, data) < 4;
data(mask) = []; %get rid of lines too short
referensi = cellfun(@(L) L(1), data);
lat = cellfun(@(L) L(2), data);
lon = cellfun(@(L) L(3), data);
means = cellfun(@(L) mean(L(4:end), 'omitnan'), data);
msl = [referensi(:), lat(:), lon(:), means(:)];
file_name = ['Msl_' ff];
dlmwrite(file_name, msl, 'delimiter', '\t');
end
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!