0

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.

2 Answers 2

1
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.
Sign up to request clarification or add additional context in comments.

2 Comments

@Kat on Stack Overflow please ask only a single question per post. For a new question, make a new post. In this case though, I'd recommend reading the MathWork's own tutorial, as this is about as basic as it goes. I presume you know how to call functions (you actually already do in your script), and had an idea why you wanted one.
Matlab functions are normally created as separate files, go to create a new function and place your function declaration there. Save the file within your working directory. Once the function is saved you can call it by its name from within any script in the working directory, without the need to "import" anything
0

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.