how to calculate mean value in each row of data?
60 views (last 30 days)
Show older comments
Retno Purwaningsih
on 20 Oct 2021
Commented: Retno Purwaningsih
on 20 Oct 2021
Hello everyone, i want to ask some help with my script.
I have a file with different number of column in each row, and i want to calculate the mean value of each row start from column 4 to end than write it in the new file.
This is my script
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);
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
But i'm facing 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);
Thanks for helping me
0 Comments
Accepted Answer
Cris LaPierre
on 20 Oct 2021
Use mean and specify the dimension (1=down rows, 2=across columns)
5 Comments
Cris LaPierre
on 20 Oct 2021
Ah, I see you are using R2017a. The syntax was slightly different back then.
data = readtable('full_Data_Cryosat_c2p0004.txt','HeaderLines',0)
mData = mean(data{:,4:end},2,'omitnan')
More Answers (0)
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!