Kat
Kat

Reputation: 27

How to change a script to a function?

I've got a set of data in an excel sheet that I've imported onto MATLAB however there are NaNs within that set of data. I've figured out some code in the main script to replace the NaN's into the wanted values:

max = x(:, 2);
min = x(:, 3);
for j = 1:length(max)
 for k = 1:length(min)
   if isnan (max(j))
     max (j) = ((max(j-1)+max(j+1))/2);
   elseif isnan (min(k))
     min (k) = ((min(k-1)+min(k+1))/2);
   end
 end
end

However, I need to be able to turn this code into a user-defined function and call it from the main script instead of having all the calculations on the main script.

I've tried to start making the function:

function [missingmax, missingmin] = missing(max, min)

However, I could not figure the rest out.

Upvotes: 0

Views: 82

Answers (2)

Antoine T
Antoine T

Reputation: 52

Since you do a linear interpolation, you don't need to define a function here. It already exists in Matlab : fillmissing

So you can replace missing values in x like that

x_filled = fillmissing(x,'linear')

Upvotes: 0

Adriaan
Adriaan

Reputation: 18177

function [max_x, min_x] = missing(x)
max_x = x(:, 2);
min_x = x(:, 3);
for jj = 1:length(max_x)
    for kk = 1:length(min_x)
        if isnan (max_x(jj))
            max_x (jj) = ((max_x(jj-1)+max_x(jj+1))/2);
        elseif isnan (min_x(kk))
            min_x (kk) = ((min_x(kk-1)+min_x(kk+1))/2);
        end
    end
end
end

You were on the right track. Couple of things:

  1. Your input is x, not min,max
  2. Your outputs are min and max, not missingmax and missingmin
  3. j denotes the imaginary unit It's not recommended for use as a variable, hence I changed it.
  4. You called variables min and max. Don't do that. Ever. Seriously. Don't. If you manage to do min=4 and then try to calculate the minimum of an array, you'll get a bunch of errors. Basically: never use the name of a build-in function for a variable.

Upvotes: 1

Related Questions