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

Time:06-03

I'm trying to perform the least-squares regression to check whether the optimal parameters of my distribution are approximately equal to the ones used to generate the random numbers.

I generated a probability density function on a histogram obtained by taking random points from the same distribution and I am trying to perform least-squares regression but I am having problems with dimension inconsistency.

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)

When I try to run this, I get an error stating

Dimensions of arrays being concatenated are not consistent.

But when I check y_ and x_, both have the same size. What is the problem?

CodePudding user response:

In your code

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

the statement ones(length(y_),1) is creating a 49x1 column vector, while x is a 1x49 row vector. So you need to one or the other of the below to concatenate depending on whether you want a 2-row or 2-column matrix

H = [ones(length(y_),1),x_'];   % creates a 49x2
H = [ones(1,length(y_)),x_];   % creates a 2x49
  • Related