Linspace to logspace smoothing

16 views (last 30 days)
Marco Clementi
Marco Clementi on 14 Jul 2023
Answered: Supraja on 27 Jul 2023
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!

Answers (1)

Supraja
Supraja on 27 Jul 2023
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!

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!