[英]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:
几件事:
x
, not min,max
x
,而不是min,max
min
and max
, not missingmax
and missingmin
min
和max
,而不是missingmax
和missingmin
j
denotes the imaginary unit It's not recommended for use as a variable, hence I changed it. j
表示虚数单位不推荐用作变量,因此我更改了它。min
and max
.min
和max
。 Don't do that.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.