MATLAB var(A) 和 mean(A) 误差.下标索引必须是实正整数或逻辑



我确信我以前使用过这个函数并且它工作得很好,但是我对正在发生的事情感到困惑。我什至无法从 mathworks.com 运行示例代码。

Variance of Matrix
Create a matrix and compute its variance.
A = [4 -7 3; 1 4 -2; 10 7 9];
var(A)
Copyright 2015 The MathWorks, Inc.

给我:

下标索引必须是实数正整数或逻辑。

这是我的特定代码...它只是给出了均值和方差计算的错误:

%2a
% Create distribution objects with different parameters
pd1 = makedist('Uniform','lower',-2,'upper',3)
% Compute the pdfs
x = -3:0.1:4;
pdf1 = pdf(pd1,x);
% Plot the pdfs
subplot(2,2,1);
plot(x,pdf1)
title('pdf of uniform RV [-2,3]');
ylim([0 0.3]);
% Compute the cdfs
x = -3:.01:4;
cdf1 = cdf(pd1,x);
% Plot the cdfs
subplot (2,2,2);
plot(x,cdf1)
title('CDF of uniform RV[-2,3]');
ylim([0 1.1]);
up = 3
low = -2
mean = (1/2)*(low + up)
var = (1/12)*(up-low)^2

% Do an actual numeric simulation
N=100000;
A = random(pd1,N,1);
[count edges] = histcounts(A,100);
count = [0 count 0];
edges = [-2.1 edges 3];
subplot(2,2,3)
plot(edges(2:end),count/N)
axis([-4 4 0 .02])
CDF = cumsum(count/N);
subplot(2,2,4)
plot(edges(2:end),CDF)
axis([-4 4 0 1.2])
m1 = sum(A)/N
v1 = var(A,0,1)
% Create distribution objects with different parameters
pd2 = makedist('Normal','mu',2,'sigma',sqrt(2.25))
% Compute the pdfs
x = -3:0.1:7;
pdf1 = pdf(pd2,x);
% Plot the pdfs
subplot(2,2,1);
plot(x,pdf1)
title('pdf');
axis([-4 7 0 .05])
ylim([0 0.3]);
% Compute the cdfs
x = -3:.01:4;
cdf1 = cdf(pd2,x);
% Plot the cdfs
subplot (2,2,2);
plot(x,cdf1)
title('CDF');
axis([-4 7 0 1.2])
%ylim([0 1.1]);
up = 3
low = -2
mean = (1/2)*(low + up)
var = (1/12)*(up-low)^2

% Do an actual numeric simulation
N=100000;
A = random(pd2,N,1);
[count edges] = histcounts(A,100);
count = [0 count 0];
edges = [-2.1 edges 3];
subplot(2,2,3)
plot(edges(2:end),count/N)
axis([-4 7 0 .05])
CDF = cumsum(count/N);
subplot(2,2,4)
plot(edges(2:end),CDF)
axis([-4 7 0 1.2])
m2 = mean(A)
v2 = var(A)

您已经定义了与 Matlab mean() 和 var() 函数同名的变量。

mean = (1/2)*(low + up)
var = (1/12)*(up-low)^2
这将导致 Matlab 将

随后调用 Matlab 的 mean() 和 var() 函数的尝试解释为尝试使用矩阵 A 索引用户定义的变量,这将导致您看到的错误消息:

下标索引必须是实正整数或逻辑

解决方案是将用户定义的变量重命名为 Matlab 均值和变量函数(或 Matlab 中的任何其他保留函数名称)以外的名称,以确保变量名称不会与 Matlab 函数名称冲突。如果您不确定,请使用 Matlab 的 WHAT 来检查可能的变量名称是否存在冲突。

类似的东西

my_mean = (1/2)*(low + up)
my_var = (1/12)*(up-low)^2

最新更新