连接的数组的维度不一致,但两个数组的大小相同

Dimensions of arrays being concatenated are not consistent but both arrays have the same size

我正在尝试执行最小二乘回归来检查我的分布的最优参数是否近似等于用于生成随机数的参数。

我在直方图上生成了一个概率密度函数,该直方图是通过从同一分布中随机取点而获得的,我正在尝试执行最小二乘回归,但我遇到了维度不一致的问题。

N = 10000;
mu = 5; sigma = 2;
r = randn(N,1);
x = mu+sigma*r;
bin=mu-6*sigma:0.5:mu+6*sigma;
[~,centers]=hist(x,bin);
f=hist(x,bin);
plot(bin,f,'bo'); hold on;
xlabel('bin');
ylabel('f');

y_ = f;
x_ = bin;

H = [ones(length(y_),1),x_];   % This is the problem

% Least-Squares Regression
Astar = inv(H'*H)*H'*y_;
Ytilde = H*Astar;
plot(x_,Ytilde, 'r-','LineWidth',2)

当我尝试 运行 时,我收到一条错误消息

Dimensions of arrays being concatenated are not consistent.

但是当我检查 y_ 和 x_ 时,它们的大小相同。有什么问题?

在你的代码中

H = [ones(length(y_),1),x_];   % This is the problem

语句 ones(length(y_),1) 正在创建一个 49x1 列向量,而 x 是一个 1x49 行向量。因此,您需要根据您想要的是 2 行矩阵还是 2 列矩阵

来连接下面的一个或另一个
H = [ones(length(y_),1),x_'];   % creates a 49x2
H = [ones(1,length(y_)),x_];   % creates a 2x49