MATLAB: Unable to perform assignment because the left and right sides have a different number of elements.

subtractive clustering

for i = 1:n
for j =1:n
if(i~=j)
P(i) = P(i) + exp(-abs(X(:,:,i) - X(:,:,j)).^2 / (ra / 2).^2);
end
end
end
another Type of code that also show this message:
m = length(X(:,:,i));
xones = ones(1, m);
P = zeros(1, m);
for i = 1:n
P(i) = sum(exp(-(abs(xones*X(:,:,i) - X).^2)/((ra / 2)^2)));
end
please help.

Best Answer

P(i) = P(i) + exp(-abs(X(:,:,i) - X(:,:,j)).^2 / (ra / 2).^2);
The X(:,:,i) and X(:,:,j) parts look a lot like X(:,:,i) is expected to be 2 dimensional. That would make the subtraction 2 dimensional result, and the whole right side of the + would appear to create a two dimensional result. The left hand side of the + is a scalar, and scalar plus 2D gives 2D. So the calculation is 2D but you are trying to store it into a scalar location.
P(i) = sum(exp(-(abs(xones*X(:,:,i) - X).^2)/((ra / 2)^2)));
X(:,:,i) looks like 2D and we deduce that X itself is 3D. xones is 1 x m, and if you not getting an error about matrix dimensions must agree then we can figure that X must be m by something by something_else . 1 x m * m x something x 1 gives 1 x m so we can figure that xones*X(:,:,i) is 1 x m. From that we subtract m x something by something_else . That would be an error unless the "something" is also m, which we do not know for sure because length(X(:,:,m)) could be either size(X,1) or size(X,2) depending which is larger. But if we hypothesize that X is m x m x something_else then 1 x m minus m x m x something_else can work in R2016b or later, being equivalent to bsxfun(@minus, xones*X(:,:,i), X) and giving a m x m x something_else result. You then sum() that along the first dimension, giving a 1 x m x something_else result, and you try to store that multi-dimensional array into the scalar location P(i)