简体   繁体   English

如何将脚本更改为函数?

[英]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.我在导入到 MATLAB 的 Excel 表中有一组数据,但是该组数据中有 NaN。 I've figured out some code in the main script to replace the NaN's into the wanted values:我在主脚本中找到了一些代码来将 NaN 替换为所需的值:

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.但是,我无法弄清楚其余部分。

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您的输入是x ,而不是min,max
  2. Your outputs are min and max , not missingmax and missingmin你的输出是minmax ,而不是missingmaxmissingmin
  3. j denotes the imaginary unit It's not recommended for use as a variable, hence I changed it. j表示虚数单位不推荐用作变量,因此我更改了它。
  4. You called variables min and max .您调用了变量minmax 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.如果你设法做min=4然后尝试计算数组的最小值,你会得到一堆错误。 Basically: never use the name of a build-in function for a variable.基本上:永远不要为变量使用内置函数的名称。

Since you do a linear interpolation, you don't need to define a function here.由于您进行了线性插值,因此您无需在此处定义函数。 It already exists in Matlab : fillmissing它已经存在于 Matlab 中: fillmissing

So you can replace missing values in x like that所以你可以像这样替换x缺失值

x_filled = fillmissing(x,'linear')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM