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

채택된 답변

Walter Roberson
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)
ans = 1×2
494 31
means = mean(padded(:,4:end), 'omitnan')
means = 1×28
0.9759 0.7547 0.9479 0.9733 1.2691 1.4854 1.7781 1.6963 1.5994 1.3001 1.1438 1.0408 1.0178 0.9148 0.8020 0.9430 1.2950 1.1150 0.9660 NaN 1.1100 1.1120 0.8370 0.8440 1.0500 0.7850 0.6400 0.9590
  댓글 수: 7
Retno Purwaningsih
Retno Purwaningsih 2021년 10월 1일
i used script from your latest comment but still face an error like this
Error using cellfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
Error in script_msl (line 13)
data = cellfun(@(s) sscanf(s, '%f', [1 inf]), S);
Thankss for the answer
Walter Roberson
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개)

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by