MATLAB: In an assignment A(I) = B, the number of elements in B and I must be the same, error.

loop

x =
4
5
6
7
8 %5x1
X =
1
2
3
4
5
6 %6x1
q=6;
for i=1:q
dk(i)=x-X(i)
end
%it gives me the error.
%in this statement, I wanna create this situation,
dk(1)=x-X(1)
dk(2)=x-X(2)
dk(3)=x-X(3)
dk(4)=x-X(4)
dk(5)=x-X(5)
dk(6)=x-X(6)
What kind of loop I need to create these "dk".

Best Answer

x - vector -> dk1 = x-X(1), here dk1 - vector with length of x
in your case dk - matrix with size 6 x 5:
dk = zeros(numel(X),numel(x));
for jj = 1:numel(X)
dk(jj,:) = x - X(jj);
end
or
dk = bsxfun(@minus,x(:)',X(:));