我想将 R 中的代码转换为 MATLAB(而不是在 MATLAB 中执行 R 代码)。 R中的代码如下:
data_set <- read.csv("lab01_data_set.csv")
# get x and y values
x <- data_set$x
y <- data_set$y
# get number of classes and number of samples
K <- max(y)
N <- length(y)
# calculate sample means
sample_means <- sapply(X = 1:K, FUN = function(c) {mean(x[y == c])})
# calculate sample deviations
sample_deviations <- sapply(X = 1:K, FUN = function(c) {sqrt(mean((x[y == c] - sample_means[c])^2))})
为了在 MATLAB 中实现它,我编写了以下内容:
%% Reading Data
% read data into memory
X=readmatrix("lab01_data_set(ViaMatlab).csv");
% get x and y values
x_read=X(1,:);
y_read=X(2,:);
% get number of classes and number of samples
K = max(y_read);
N = length(y_read);
% Calculate sample mean - 1st method
% funct1 = @(c) mean(c);
% G1=findgroups(y_read);
% sample_mean=splitapply(funct1,x_read,G1)
% Calculate sample mean - 2nd method
for m=1:3
sample_mean(1,m)=mean(x(y_read == m));
end
sample_mean;
% Calculate sample deviation - 2nd method
for m=1:3
sample_mean=mean(x(y_read == m));
sample_deviation(1,m)=sqrt(mean((x(y_read == m)-sample_mean).^2));
sample_mean1(1,m)=sample_mean;
end
sample_deviation;
sample_mean1;
如您所见,我了解如何在 MATLAB 中使用 for 循环,而不是在 R 中使用 sapply
(作为代码中的第二种方法),但不知道如何使用函数(可能 splitaplly
或任何其他)。
PS:不知道如何上传数据,对此部分感到抱歉。
最佳答案
与 R sapply
等效的 MATLAB 是 arrayfun
- 及其相关的 cellfun
、structfun
和 varfun
取决于您输入的数据类型。
例如,在 R 中:
> sapply(1:3, function(x) x^2)
[1] 1 4 9
相当于 MATLAB:
>>> arrayfun(@(x) x^2, 1:3)
ans =
1 4 9
请注意,如果您传递给 arrayfun
、cellfun
等的函数结果对于每个输入都没有相同的类型或大小,则您需要指定 'UniformOutput', 'false'
。
关于r - MATLAB 中 R 对应项中的 "Sapply"函数,用于将代码从 R 转换为 MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58168329/