MATLAB: How to create a specific matrix in a for loop

for loopMATLABmatrix

Hi,
I have a 4×50 matrix which is defined as x. I'm trying to store each row of x inside each row of b with a formula that is stated in the code below. So, each row of b is predetermined with the corresponding row of x. After creating the matrix b, I will generate arrays with the code ndgrid. I keep getting the error "Subscripted assignment dimension mismatch." when it comes to the for loop. How I can get around this problem? Thank you very much in advance.
[M N] = size(x); % M number of rows, N number of column
b = zeros(M,N);
b(1,:) = x(1,:);
for j=1:1:M-1
b(j,:) = [min(x(j,:)):(max(x(j,:))-min(x(j,:)))/20:max(x(j,:))];
end
binscenter(1:M,:) = ndgrid(b(1:M,:));
Edit: Also in the last line with the code ndgrid, how can I generate arrays? I don't think my code is going to work, since I didn't specify what binscenter is. The problem is, number of rows and columns of x can change under different circumstances. So I'm trying to write a more compact code which calculates number of rows of x and than binscenter is determined accordingly.

Best Answer

The right-hand side of your assignment statement inside the for loop is creating a vector that is length 21, and the right-hand side is length 50. That is the mismatch.
Instead of "20", you need "N-1" there.
You might still need to be careful in how you constructed that statement, because creating vectors like that can lead to unexpected results when using floating point numbers. I suggest you use the linspace() function to do that operation:
linspace(min(x(j,:)),max(x(j,:)),N)
should do what you want.