Help creating a non-intrinsic smoothing function.

4 visualizzazioni (ultimi 30 giorni)

So I have to create a smoothing function of some random data that roughly plots a cosine wave. I have been given the following pseudocode to work with but am having trouble interpreting the second and third, for's:

  • If width=5 and length(x)=100, then for n=3:98, smoothed(n)=mean(x(n-2:n+2)); for n<3, smoothed(1)=x(1); smoothed(2)=mean(x(1),x(2),x(3)); for n>98, smoothed(99)=mean(x(98),x(99),x(100)); smoothed(100)=x(100).

This works for the first for but when it generates a vector, its first two values are 0 and the last 2 arent even included.

Here is the current code I have:

t = linspace(0,1,100); 
noise = rand(1,length(t));
x = cos(2*pi*t) + 0.5*(rand(size(noise))-0.5);
width=5;
smoothed=CTask2p1_f(x, width)
figure
hold on
plot(t,x,'bo')
plot(t,smoothed,'r-')

and my function

    function smoothed = CTask2p1_f(x,width)
    if width == 5 && length(x) == 100
        for n=3:98
            smoothed(n)=mean(x(n-2:n+2));
        end
        while n < 3
            smoothed(1)=x(1);
            smoothed(2)=mean(x(1),x(2),x(3));
        end
        while n > 98
            smoothed(99)=mean(x(98),x(99),x(100));
            smoothed(100)=x(100);
        end
    end

I am not sure what is causing the issue here. I have two while loops as an error occurs if I use for instead of while on the greater than less than parts. Help will be greatly appreciated.

Risposta accettata

Walter Roberson
Walter Roberson il 19 Apr 2018
Your while loops are not changing n, so they are infinite loops.
Your while loops are also not using the value of n, so they are repeating code for no good reason.
I would suggest you just remove the "while" on n, leaving just the assignment statements .
  4 Commenti
Kyle Oswin-Inglis
Kyle Oswin-Inglis il 19 Apr 2018
Does that work for you? Because now i'm getting more errors than before. Error using sum Dimension argument must be a positive integer scalar within indexing range.
Error in mean (line 116) y = sum(x, dim, flag) ./ size(x,dim);
Error in CTask2p1_f (line 8) smoothed(2)=mean(x(1),x(2),x(3));
Error in CTask2p1 (line 5) smoothed=CTask2p1_f(x, width)

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by