Linspace to logspace smoothing

14 次查看(过去 30 天)
Marco Clementi
Marco Clementi 2023-7-14
回答: Supraja 2023-7-27
Hi, I want to interpolate some linearly spaced data to a logarithmic grid for plotting.
The first solution I tried was:
function [f_log,data_log] = lin2log(f_lin,data_lin)
NPOINTS=1001;
f_lin=log10(f_lin);
f_log=log10(logspace(f_lin(1),f_lin(end),NPOINTS));
data_log=interp1(f_lin,data_lin,f_log);
f_new=10.^f_new;
end
However, the input data is very noisy, and I would like to also smooth it before interpolating. So I updated the code with a for loop:
function [f_log,data_log] = lin2log(f_lin,data_lin)
NPOINTS=1001;
f_lin=log10(f_lin);
f_log=log10(logspace(f_lin(1),f_lin(end),NPOINTS));
for nn=1:NPOINTS-1
inds = (f_lin>=f_log(nn) & f_lin<(f_log(nn+1)));
data_lin(inds)=mean(data_lin(inds));
end
data_log=interp1(f_lin,data_lin,f_log);
f_new=10.^f_new;
end
This worked nicely, but the loop seems to slow down the code quite a lot, especially given that the input data is a very long array.
Any suggestions on a way improve the code efficiency? Many thanks!

回答(1 个)

Supraja
Supraja 2023-7-27
You can improve you code efficiency by sorting the data and then passing it to the “interp1” function.
You can also use “smooth” function for better efficiency.
The detailed documentation link of the “interp1” function is given here:https://www.mathworks.com/help/matlab/ref/interp1.html#btwp6lt-3
You can also refer to the MATLAB Answer given here which is similar to your query:https://www.mathworks.com/support/search.html/answers/113651-how-to-smoothing-a-curve.html?fq%5B%5D=asset_type_name:answer&fq%5B%5D=category:curvefit/smoothing&page=1
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by